view.js 294 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025
  1. import * as base from './base.js';
  2. import * as grapher from './grapher.js';
  3. const view = {};
  4. const markdown = {};
  5. const metadata = {};
  6. const metrics = {};
  7. view.View = class {
  8. constructor(host) {
  9. this._host = host;
  10. this._defaultOptions = {
  11. weights: true,
  12. attributes: false,
  13. names: false,
  14. direction: 'vertical',
  15. mousewheel: 'scroll'
  16. };
  17. this._options = { ...this._defaultOptions };
  18. this._model = null;
  19. this._path = [];
  20. this._selection = [];
  21. this._sidebar = new view.Sidebar(this._host);
  22. this._find = null;
  23. this._modelFactoryService = new view.ModelFactoryService(this._host);
  24. this._modelFactoryService.import();
  25. this._worker = this._host.environment('serial') ? null : new view.Worker(this._host);
  26. }
  27. async start() {
  28. try {
  29. const zip = await import('./zip.js');
  30. await zip.Archive.import();
  31. await this._host.view(this);
  32. const options = this._host.get('options') || {};
  33. for (const [name, value] of Object.entries(options)) {
  34. this._options[name] = value;
  35. }
  36. this._element('sidebar-model-button').addEventListener('click', () => {
  37. this.showModelProperties();
  38. });
  39. this._element('sidebar-target-button').addEventListener('click', () => {
  40. this.showTargetProperties();
  41. });
  42. this._element('zoom-in-button').addEventListener('click', () => {
  43. this.zoomIn();
  44. });
  45. this._element('zoom-out-button').addEventListener('click', () => {
  46. this.zoomOut();
  47. });
  48. this._element('toolbar-path-back-button').addEventListener('click', async () => {
  49. await this.popTarget();
  50. });
  51. this._element('sidebar').addEventListener('mousewheel', (e) => {
  52. if (e.shiftKey || e.ctrlKey) {
  53. e.preventDefault();
  54. }
  55. }, { passive: false });
  56. this._host.document.addEventListener('keydown', () => {
  57. if (this._target) {
  58. this._target.select(null);
  59. }
  60. });
  61. if (this._host.type === 'Electron') {
  62. this._host.update({ 'copy.enabled': false });
  63. this._host.document.addEventListener('selectionchange', () => {
  64. const selection = this._host.document.getSelection();
  65. const selected = selection.rangeCount === 0 || selection.toString().trim() !== '';
  66. this._host.update({ 'copy.enabled': selected });
  67. });
  68. }
  69. const platform = this._host.environment('platform');
  70. this._menu = new view.Menu(this._host);
  71. this._menu.add({
  72. accelerator: platform === 'darwin' ? 'Ctrl+Cmd+F' : 'F11',
  73. execute: async () => await this._host.execute('fullscreen')
  74. });
  75. this._menu.add({
  76. accelerator: 'Backspace',
  77. execute: async () => await this.popTarget()
  78. });
  79. if (this._host.environment('menu')) {
  80. const menu = this._element('menu');
  81. const button = this._element('menu-button');
  82. this._menu.attach(menu, button);
  83. const file = this._menu.group('&File');
  84. file.add({
  85. label: '&Open...',
  86. accelerator: 'CmdOrCtrl+O',
  87. execute: async () => await this._host.execute('open')
  88. });
  89. if (this._host.type === 'Electron') {
  90. this._recents = file.group('Open &Recent');
  91. file.add({
  92. label: '&Export...',
  93. accelerator: 'CmdOrCtrl+Shift+E',
  94. execute: async () => await this._host.execute('export'),
  95. enabled: () => this.activeTarget
  96. });
  97. file.add({
  98. label: platform === 'darwin' ? '&Close Window' : '&Close',
  99. accelerator: 'CmdOrCtrl+W',
  100. execute: async () => await this._host.execute('close'),
  101. });
  102. file.add({
  103. label: platform === 'win32' ? 'E&xit' : '&Quit',
  104. accelerator: platform === 'win32' ? '' : 'CmdOrCtrl+Q',
  105. execute: async () => await this._host.execute('quit'),
  106. });
  107. } else {
  108. file.add({
  109. label: 'Export as &PNG',
  110. accelerator: 'CmdOrCtrl+Shift+E',
  111. execute: async () => await this.export(`${this._host.document.title}.png`),
  112. enabled: () => this.activeTarget
  113. });
  114. file.add({
  115. label: 'Export as &SVG',
  116. accelerator: 'CmdOrCtrl+Alt+E',
  117. execute: async () => await this.export(`${this._host.document.title}.svg`),
  118. enabled: () => this.activeTarget
  119. });
  120. }
  121. const edit = this._menu.group('&Edit');
  122. edit.add({
  123. label: '&Find...',
  124. accelerator: 'CmdOrCtrl+F',
  125. execute: () => this.find(),
  126. enabled: () => this.activeTarget
  127. });
  128. const view = this._menu.group('&View');
  129. view.add({
  130. label: () => this.options.attributes ? 'Hide &Attributes' : 'Show &Attributes',
  131. accelerator: 'CmdOrCtrl+D',
  132. execute: () => this.toggle('attributes'),
  133. enabled: () => this.activeTarget
  134. });
  135. view.add({
  136. label: () => this.options.weights ? 'Hide &Weights' : 'Show &Weights',
  137. accelerator: 'CmdOrCtrl+I',
  138. execute: () => this.toggle('weights'),
  139. enabled: () => this.activeTarget
  140. });
  141. view.add({
  142. label: () => this.options.names ? 'Hide &Names' : 'Show &Names',
  143. accelerator: 'CmdOrCtrl+U',
  144. execute: () => this.toggle('names'),
  145. enabled: () => this.activeTarget
  146. });
  147. view.add({
  148. label: () => this.options.direction === 'vertical' ? 'Show &Horizontal' : 'Show &Vertical',
  149. accelerator: 'CmdOrCtrl+K',
  150. execute: () => this.toggle('direction'),
  151. enabled: () => this.activeTarget
  152. });
  153. view.add({
  154. label: () => this.options.mousewheel === 'scroll' ? '&Mouse Wheel: Zoom' : '&Mouse Wheel: Scroll',
  155. accelerator: 'CmdOrCtrl+M',
  156. execute: () => this.toggle('mousewheel'),
  157. enabled: () => this.activeTarget
  158. });
  159. view.add({});
  160. if (this._host.type === 'Electron') {
  161. view.add({
  162. label: '&Reload',
  163. accelerator: platform === 'darwin' ? 'CmdOrCtrl+R' : 'F5',
  164. execute: async () => await this._host.execute('reload'),
  165. enabled: () => this.activeTarget
  166. });
  167. view.add({});
  168. }
  169. view.add({
  170. label: 'Zoom &In',
  171. accelerator: 'Shift+Up',
  172. execute: () => this.zoomIn(),
  173. enabled: () => this.activeTarget && this.target
  174. });
  175. view.add({
  176. label: 'Zoom &Out',
  177. accelerator: 'Shift+Down',
  178. execute: () => this.zoomOut(),
  179. enabled: () => this.activeTarget && this.target
  180. });
  181. view.add({
  182. label: 'Actual &Size',
  183. accelerator: 'Shift+Backspace',
  184. execute: () => this.resetZoom(),
  185. enabled: () => this.activeTarget && this.target
  186. });
  187. view.add({});
  188. view.add({
  189. label: '&Properties...',
  190. accelerator: 'CmdOrCtrl+Enter',
  191. execute: () => this.showTargetProperties(),
  192. enabled: () => this.activeTarget
  193. });
  194. if (this._host.type === 'Electron' && !this._host.environment('packaged')) {
  195. view.add({});
  196. view.add({
  197. label: '&Developer Tools...',
  198. accelerator: 'CmdOrCtrl+Alt+I',
  199. execute: async () => await this._host.execute('toggle-developer-tools')
  200. });
  201. }
  202. const help = this._menu.group('&Help');
  203. help.add({
  204. label: 'Report &Issue',
  205. execute: async () => await this._host.execute('report-issue')
  206. });
  207. help.add({
  208. label: `&About ${this._host.environment('name')}`,
  209. execute: async () => await this._host.execute('about')
  210. });
  211. }
  212. const navigator = this._element('toolbar-navigator');
  213. this._select = new view.TargetSelector(this, navigator);
  214. this._select.on('change', (sender, target) => this._updateActiveTarget([target]));
  215. await this._host.start();
  216. } catch (error) {
  217. this.error(error, null, null);
  218. }
  219. }
  220. get host() {
  221. return this._host;
  222. }
  223. show(page) {
  224. if (!page) {
  225. page = (!this._model && !this.activeTarget) ? 'welcome' : 'default';
  226. }
  227. this._host.event('screen_view', {
  228. screen_name: page,
  229. });
  230. if (this._sidebar) {
  231. this._sidebar.close();
  232. }
  233. if (this._menu) {
  234. this._menu.close();
  235. }
  236. this._host.document.body.classList.remove(...Array.from(this._host.document.body.classList).filter((_) => _ !== 'active'));
  237. this._host.document.body.classList.add(...page.split(' '));
  238. if (this._target && page === 'default') {
  239. this._target.register();
  240. } else if (this._target) {
  241. this._target.unregister();
  242. }
  243. if (page === 'welcome') {
  244. const element = this._element('open-file-button');
  245. if (element) {
  246. element.focus();
  247. }
  248. }
  249. this._page = page;
  250. }
  251. progress(percent) {
  252. const bar = this._element('progress-bar');
  253. if (bar) {
  254. bar.style.width = `${percent}%`;
  255. }
  256. }
  257. find() {
  258. if (this._target && this._sidebar.identifier !== 'find') {
  259. this._target.select(null);
  260. const sidebar = new view.FindSidebar(this, this._find, this.activeTarget, this.activeSignature);
  261. sidebar.on('state-changed', (sender, state) => {
  262. this._find = state;
  263. });
  264. sidebar.on('select', (sender, value) => {
  265. this._target.scrollTo(this._target.select([value]));
  266. });
  267. sidebar.on('focus', (sender, value) => {
  268. this._target.focus([value]);
  269. });
  270. sidebar.on('blur', (sender, value) => {
  271. this._target.blur([value]);
  272. });
  273. sidebar.on('activate', (sender, value) => {
  274. this._sidebar.close();
  275. this._target.scrollTo(this._target.activate(value));
  276. });
  277. this._sidebar.open(sidebar, 'Find');
  278. }
  279. }
  280. get model() {
  281. return this._model;
  282. }
  283. set model(value) {
  284. this._model = value;
  285. }
  286. get options() {
  287. return this._options;
  288. }
  289. get target() {
  290. return this._target;
  291. }
  292. set target(value) {
  293. if (this._target !== value) {
  294. if (this._target) {
  295. this._target.unregister();
  296. }
  297. const enabled = value ? true : false;
  298. this._host.update({
  299. 'zoom-reset.enabled': enabled,
  300. 'zoom-in.enabled': enabled,
  301. 'zoom-out.enabled': enabled
  302. });
  303. this._target = value;
  304. if (this._target) {
  305. this._target.register();
  306. }
  307. }
  308. }
  309. toggle(name) {
  310. switch (name) {
  311. case 'names':
  312. case 'attributes':
  313. case 'weights':
  314. this._options[name] = !this._options[name];
  315. this._reload();
  316. break;
  317. case 'direction':
  318. this._options.direction = this._options.direction === 'vertical' ? 'horizontal' : 'vertical';
  319. this._reload();
  320. break;
  321. case 'mousewheel':
  322. this._options.mousewheel = this._options.mousewheel === 'scroll' ? 'zoom' : 'scroll';
  323. break;
  324. default:
  325. throw new view.Error(`Unsupported toggle '${name}'.`);
  326. }
  327. const options = {};
  328. for (const [name, value] of Object.entries(this._options)) {
  329. if (this._defaultOptions[name] !== value) {
  330. options[name] = value;
  331. }
  332. }
  333. if (Object.entries(options).length === 0) {
  334. this._host.delete('options');
  335. } else {
  336. this._host.set('options', options);
  337. }
  338. }
  339. recents(recents) {
  340. if (this._recents) {
  341. this._recents.clear();
  342. for (let i = 0; i < recents.length; i++) {
  343. const recent = recents[i];
  344. this._recents.add({
  345. label: recent.label,
  346. accelerator: `CmdOrCtrl+${(i + 1)}`,
  347. execute: () => this._host.execute('open', recent.path)
  348. });
  349. }
  350. }
  351. }
  352. _reload() {
  353. this.show('welcome spinner');
  354. if (this._model && this._path.length > 0) {
  355. this._updateTarget(this._model, this._path).catch((error) => {
  356. if (error) {
  357. this.error(error, 'Graph update failed.', 'welcome');
  358. }
  359. });
  360. }
  361. }
  362. _timeout(delay) {
  363. return new Promise((resolve) => {
  364. setTimeout(resolve, delay);
  365. });
  366. }
  367. _element(id) {
  368. return this._host.document.getElementById(id);
  369. }
  370. zoomIn() {
  371. this._target.zoom *= 1.1;
  372. }
  373. zoomOut() {
  374. this._target.zoom *= 0.9;
  375. }
  376. resetZoom() {
  377. this._target.zoom = 1;
  378. }
  379. async error(error, name, screen) {
  380. if (this._sidebar) {
  381. this._sidebar.close();
  382. }
  383. this.exception(error, false);
  384. const repository = this._host.environment('repository');
  385. const knowns = [
  386. { message: /^Invalid value identifier/, issue: '540' },
  387. { message: /^Cannot read property/, issue: '647' },
  388. { message: /^Duplicate value /, issue: '1364' },
  389. { message: /^EPERM: operation not permitted/, issue: '551' },
  390. { message: /^EACCES: permission denied/, issue: '504' },
  391. { message: /^Offset is outside the bounds of the DataView/, issue: '563' },
  392. { message: /^Invalid string length/, issue: '648' },
  393. { message: /^Unknown function /, issue: '546' },
  394. { message: /^Unsupported file content/, issue: '550' },
  395. { message: /^Unsupported Protocol Buffers content/, issue: '593' },
  396. { message: /^Unsupported Protocol Buffers text content/, issue: '594' },
  397. { message: /^Unsupported JSON content/, issue: '595' },
  398. { message: /^Unknown type name '__torch__\./, issue: '969' },
  399. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto \(Unexpected end of file\)\./, issue: '1155' },
  400. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto \(Cannot read properties of undefined \(reading 'ModelProto'\)\)\./, issue: '1156' },
  401. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto/, issue: '549' }
  402. ];
  403. const known = knowns.find((known) => (!known.name || known.name === error.name) && error.message.match(known.message));
  404. const url = known && known.issue ? `${repository}/issues/${known.issue}` : `${repository}/issues`;
  405. const message = error.message;
  406. name = name || error.name;
  407. const report = !message.startsWith('Invalid file content.') && this.host.environment('packaged');
  408. await this._host.message(message, true, report ? 'Report' : 'OK');
  409. if (report) {
  410. this._host.openURL(url);
  411. }
  412. this.show(screen);
  413. }
  414. accept(file, size) {
  415. return this._modelFactoryService.accept(file, size);
  416. }
  417. async open(context) {
  418. this._sidebar.close();
  419. await this._timeout(2);
  420. try {
  421. const model = await this._modelFactoryService.open(context);
  422. const format = [];
  423. if (model.format) {
  424. format.push(model.format);
  425. }
  426. if (model.producer) {
  427. format.push(`(${model.producer})`);
  428. }
  429. if (format.length > 0) {
  430. this._host.event('model_open', {
  431. model_format: model.format || '',
  432. model_producer: model.producer || ''
  433. });
  434. }
  435. await this._timeout(20);
  436. const path = [];
  437. if (Array.isArray(model.modules) && model.modules.length > 0) {
  438. const [graph] = model.modules;
  439. const signature = Array.isArray(graph.signatures) && graph.signatures.length > 0 ? graph.signatures[0] : null;
  440. path.push({ target: graph, signature });
  441. } else if (Array.isArray(model.functions) && model.functions.length > 0) {
  442. path.push({ target: model.functions[0], signature: null });
  443. }
  444. return await this._updateTarget(model, path);
  445. } catch (error) {
  446. error.context = !error.context && context && context.identifier ? context.identifier : error.context || '';
  447. throw error;
  448. }
  449. }
  450. async attach(context) {
  451. if (this._model) {
  452. const attachment = new metadata.Attachment();
  453. if (await attachment.open(context)) {
  454. this._model.attachment = attachment;
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. async _updateActiveTarget(stack) {
  461. this._sidebar.close();
  462. if (this._model) {
  463. this.show('welcome spinner');
  464. try {
  465. await this._updateTarget(this._model, stack);
  466. } catch (error) {
  467. if (error) {
  468. this.error(error, 'Graph update failed.', 'welcome');
  469. }
  470. }
  471. }
  472. }
  473. get activeTarget() {
  474. if (this._path.length > 0) {
  475. return this._path[0].target;
  476. }
  477. return null;
  478. }
  479. get activeSignature() {
  480. if (this._path.length > 0) {
  481. return this._path[0].signature;
  482. }
  483. return null;
  484. }
  485. async _updateTarget(model, path) {
  486. const lastModel = this._model;
  487. const lastPath = this._path;
  488. try {
  489. await this._updatePath(model, path);
  490. return this._model;
  491. } catch (error) {
  492. await this._updatePath(lastModel, lastPath);
  493. throw error;
  494. }
  495. }
  496. async _updatePath(model, stack) {
  497. this.model = model;
  498. this._path = stack;
  499. const status = await this.render(this.activeTarget, this.activeSignature);
  500. if (status === 'cancel') {
  501. this.model = null;
  502. this._path = [];
  503. this._activeTarget = null;
  504. }
  505. this.show(null);
  506. const path = this._element('toolbar-path');
  507. const back = this._element('toolbar-path-back-button');
  508. while (path.children.length > 1) {
  509. path.removeChild(path.lastElementChild);
  510. }
  511. if (status === '') {
  512. if (this._path.length <= 1) {
  513. back.style.opacity = 0;
  514. } else {
  515. back.style.opacity = 1;
  516. const last = this._path.length - 2;
  517. const count = Math.min(2, last);
  518. if (count < last) {
  519. const element = this._host.document.createElement('button');
  520. element.setAttribute('class', 'toolbar-path-name-button');
  521. element.innerHTML = '&hellip;';
  522. path.appendChild(element);
  523. }
  524. for (let i = count; i >= 0; i--) {
  525. const target = this._path[i].target;
  526. const element = this._host.document.createElement('button');
  527. element.setAttribute('class', 'toolbar-path-name-button');
  528. element.addEventListener('click', async () => {
  529. if (i > 0) {
  530. this._path = this._path.slice(i);
  531. await this._updateTarget(this._model, this._path);
  532. } else {
  533. await this.showTargetProperties(target);
  534. }
  535. });
  536. let name = '';
  537. if (target && target.identifier) {
  538. name = target.identifier;
  539. } else if (target && target.name) {
  540. name = target.name;
  541. }
  542. if (name.length > 24) {
  543. element.setAttribute('title', name);
  544. const truncated = name.substring(name.length - 24, name.length);
  545. element.innerHTML = '&hellip;';
  546. const text = document.createTextNode(truncated);
  547. element.appendChild(text);
  548. } else {
  549. element.removeAttribute('title');
  550. element.textContent = name;
  551. }
  552. path.appendChild(element);
  553. }
  554. }
  555. this._select.update(model, stack);
  556. const button = this._element('sidebar-target-button');
  557. if (stack.length > 0) {
  558. const type = stack[stack.length - 1].type || 'graph';
  559. const name = type.charAt(0).toUpperCase() + type.slice(1);
  560. button.setAttribute('title', `${name} Properties`);
  561. button.style.display = 'block';
  562. } else {
  563. button.style.display = 'none';
  564. }
  565. }
  566. }
  567. async pushTarget(graph, context) {
  568. if (graph && graph !== this.activeTarget && Array.isArray(graph.nodes)) {
  569. this._sidebar.close();
  570. if (context && this._path.length > 0) {
  571. this._path[0].state = { context, zoom: this._target.zoom };
  572. }
  573. const signature = Array.isArray(graph.signatures) && graph.signatures.length > 0 ? graph.signatures[0] : null;
  574. const entry = { target: graph, signature };
  575. const stack = [entry].concat(this._path);
  576. await this._updateTarget(this._model, stack);
  577. }
  578. }
  579. async popTarget() {
  580. if (this._path.length > 1) {
  581. this._sidebar.close();
  582. return await this._updateTarget(this._model, this._path.slice(1));
  583. }
  584. return null;
  585. }
  586. async render(target, signature) {
  587. this.target = null;
  588. const element = this._element('target');
  589. while (element.lastChild) {
  590. element.removeChild(element.lastChild);
  591. }
  592. let status = '';
  593. if (target) {
  594. const document = this._host.document;
  595. const graph = target;
  596. const groups = graph.groups || false;
  597. const nodes = graph.nodes;
  598. this._host.event('graph_view', {
  599. graph_node_count: nodes.length,
  600. graph_skip: 0
  601. });
  602. const viewGraph = new view.Graph(this, groups);
  603. viewGraph.add(graph, signature);
  604. viewGraph.build(document);
  605. await viewGraph.measure();
  606. status = await viewGraph.layout(this._worker);
  607. if (status === '') {
  608. viewGraph.update();
  609. const state = this._path && this._path.length > 0 && this._path[0] && this._path[0].state ? this._path[0].state : null;
  610. viewGraph.restore(state);
  611. this.target = viewGraph;
  612. }
  613. }
  614. return status;
  615. }
  616. async export(file) {
  617. const lastIndex = file.lastIndexOf('.');
  618. const extension = lastIndex === -1 ? 'png' : file.substring(lastIndex + 1).toLowerCase();
  619. if (this.activeTarget && (extension === 'png' || extension === 'svg')) {
  620. const canvas = this._element('canvas');
  621. const clone = canvas.cloneNode(true);
  622. const document = this._host.document;
  623. const applyStyleSheet = (element, name) => {
  624. let rules = [];
  625. for (const styleSheet of document.styleSheets) {
  626. if (styleSheet && styleSheet.href && styleSheet.href.endsWith(`/${name}`)) {
  627. rules = styleSheet.cssRules;
  628. break;
  629. }
  630. }
  631. const nodes = element.getElementsByTagName('*');
  632. for (const node of nodes) {
  633. for (const rule of rules) {
  634. if (node.matches(rule.selectorText)) {
  635. for (const item of rule.style) {
  636. node.style[item] = rule.style[item];
  637. }
  638. }
  639. }
  640. }
  641. };
  642. applyStyleSheet(clone, 'grapher.css');
  643. clone.setAttribute('id', 'export');
  644. clone.removeAttribute('viewBox');
  645. clone.removeAttribute('width');
  646. clone.removeAttribute('height');
  647. clone.style.removeProperty('opacity');
  648. clone.style.removeProperty('display');
  649. clone.style.removeProperty('width');
  650. clone.style.removeProperty('height');
  651. const background = clone.querySelector('#background');
  652. clone.getElementById('edge-paths-hit-test').remove();
  653. const origin = clone.querySelector('#origin');
  654. origin.setAttribute('transform', 'translate(0,0) scale(1)');
  655. background.removeAttribute('width');
  656. background.removeAttribute('height');
  657. const parent = canvas.parentElement;
  658. parent.insertBefore(clone, canvas);
  659. const size = clone.getBBox();
  660. parent.removeChild(clone);
  661. parent.removeChild(canvas);
  662. parent.appendChild(canvas);
  663. const delta = (Math.min(size.width, size.height) / 2.0) * 0.1;
  664. const width = Math.ceil(delta + size.width + delta);
  665. const height = Math.ceil(delta + size.height + delta);
  666. origin.setAttribute('transform', `translate(${(delta - size.x)}, ${(delta - size.y)}) scale(1)`);
  667. clone.setAttribute('width', width);
  668. clone.setAttribute('height', height);
  669. background.setAttribute('width', width);
  670. background.setAttribute('height', height);
  671. background.setAttribute('fill', '#fff');
  672. const data = new XMLSerializer().serializeToString(clone);
  673. if (extension === 'svg') {
  674. const blob = new Blob([data], { type: 'image/svg' });
  675. await this._host.export(file, blob);
  676. }
  677. if (extension === 'png') {
  678. try {
  679. const blob = await new Promise((resolve, reject) => {
  680. const image = new Image();
  681. image.onload = async () => {
  682. const max = Math.max(width, height);
  683. const scale = Math.min(24000.0 / max, 2.0);
  684. const canvas = this._host.document.createElement('canvas');
  685. canvas.width = Math.ceil(width * scale);
  686. canvas.height = Math.ceil(height * scale);
  687. const context = canvas.getContext('2d');
  688. context.scale(scale, scale);
  689. context.drawImage(image, 0, 0);
  690. canvas.toBlob((blob) => {
  691. if (blob) {
  692. resolve(blob);
  693. } else {
  694. const error = new Error('Image may be too large to render as PNG.');
  695. error.name = 'Error exporting image.';
  696. reject(error);
  697. }
  698. }, 'image/png');
  699. };
  700. image.onerror = (error) => {
  701. reject(error);
  702. };
  703. image.src = `data:image/svg+xml;base64,${this._host.window.btoa(unescape(encodeURIComponent(data)))}`;
  704. });
  705. await this._host.export(file, blob);
  706. } catch (error) {
  707. await this.error(error);
  708. }
  709. }
  710. }
  711. }
  712. showModelProperties() {
  713. if (!this._model) {
  714. return;
  715. }
  716. try {
  717. const sidebar = new view.ModelSidebar(this, this.model);
  718. this._sidebar.open(sidebar, 'Model Properties');
  719. } catch (error) {
  720. this.error(error, 'Error showing model properties.', null);
  721. }
  722. }
  723. showTargetProperties() {
  724. if (this._sidebar.identifier === 'target') {
  725. this.showModelProperties();
  726. return;
  727. }
  728. const target = this.activeTarget;
  729. if (!target) {
  730. return;
  731. }
  732. try {
  733. const sidebar = new view.TargetSidebar(this, target, this.activeSignature);
  734. sidebar.on('show-definition', async (/* sender, e */) => {
  735. await this.showDefinition(target);
  736. });
  737. sidebar.on('focus', (sender, value) => {
  738. this._target.focus([value]);
  739. });
  740. sidebar.on('blur', (sender, value) => {
  741. this._target.blur([value]);
  742. });
  743. sidebar.on('select', (sender, value) => {
  744. this._target.scrollTo(this._target.select([value]));
  745. });
  746. sidebar.on('activate', (sender, value) => {
  747. this._target.scrollTo(this._target.activate(value));
  748. });
  749. sidebar.on('deactivate', () => {
  750. this._target.select(null);
  751. });
  752. let title = null;
  753. const type = target.type || 'graph';
  754. switch (type) {
  755. case 'graph':
  756. title = 'Graph Properties';
  757. break;
  758. case 'function':
  759. title = 'Function Properties';
  760. break;
  761. case 'weights':
  762. title = 'Weights Properties';
  763. break;
  764. default:
  765. throw new view.Error(`Unsupported graph type '${type}'.`);
  766. }
  767. this._sidebar.open(sidebar, title);
  768. } catch (error) {
  769. this.error(error, 'Error showing target properties.', null);
  770. }
  771. }
  772. showNodeProperties(node) {
  773. if (node) {
  774. try {
  775. if (this._menu) {
  776. this._menu.close();
  777. }
  778. const sidebar = new view.NodeSidebar(this, node);
  779. sidebar.on('show-definition', async (/* sender, e */) => {
  780. await this.showDefinition(node.type);
  781. });
  782. sidebar.on('focus', (sender, value) => {
  783. this._target.focus([value]);
  784. });
  785. sidebar.on('blur', (sender, value) => {
  786. this._target.blur([value]);
  787. });
  788. sidebar.on('select', (sender, value) => {
  789. this._target.scrollTo(this._target.select([value]));
  790. });
  791. sidebar.on('activate', (sender, value) => {
  792. this._target.scrollTo(this._target.activate(value));
  793. });
  794. this._sidebar.open(sidebar, 'Node Properties');
  795. } catch (error) {
  796. this.error(error, 'Error showing node properties.', null);
  797. }
  798. }
  799. }
  800. showConnectionProperties(value, from, to) {
  801. try {
  802. if (this._menu) {
  803. this._menu.close();
  804. }
  805. const sidebar = new view.ConnectionSidebar(this, value, from, to);
  806. sidebar.on('focus', (sender, value) => {
  807. this._target.focus([value]);
  808. });
  809. sidebar.on('blur', (sender, value) => {
  810. this._target.blur([value]);
  811. });
  812. sidebar.on('select', (sender, value) => {
  813. this._target.scrollTo(this._target.select([value]));
  814. });
  815. sidebar.on('activate', (sender, value) => {
  816. this._target.scrollTo(this._target.activate(value));
  817. });
  818. this._sidebar.push(sidebar, 'Connection Properties');
  819. } catch (error) {
  820. this.error(error, 'Error showing connection properties.', null);
  821. }
  822. }
  823. showTensorProperties(value) {
  824. try {
  825. if (this._menu) {
  826. this._menu.close();
  827. }
  828. const sidebar = new view.TensorSidebar(this, value);
  829. sidebar.on('focus', (sender, value) => {
  830. this._target.focus([value]);
  831. });
  832. sidebar.on('blur', () => {
  833. this._target.blur(null);
  834. });
  835. sidebar.on('select', (sender, value) => {
  836. this._target.scrollTo(this._target.select([value]));
  837. });
  838. sidebar.on('activate', (sender, value) => {
  839. this._target.scrollTo(this._target.activate(value));
  840. });
  841. this._sidebar.push(sidebar, 'Tensor Properties');
  842. } catch (error) {
  843. this.error(error, 'Error showing tensor properties.', null);
  844. }
  845. }
  846. exception(error, fatal) {
  847. if (error && !error.context && this._model && this._model.identifier) {
  848. error.context = this._model.identifier;
  849. }
  850. this._host.exception(error, fatal);
  851. }
  852. async showDefinition(type) {
  853. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  854. if (type.nodes && type.nodes.length > 0) {
  855. await this.pushTarget(type);
  856. }
  857. if (type.type !== 'weights') {
  858. const sidebar = new view.DocumentationSidebar(this, type);
  859. sidebar.on('navigate', (sender, e) => {
  860. this._host.openURL(e.link);
  861. });
  862. const title = type.type === 'function' ? 'Function Documentation' : 'Documentation';
  863. this._sidebar.push(sidebar, title);
  864. }
  865. }
  866. }
  867. about() {
  868. this._host.document.getElementById('version').innerText = this._host.version;
  869. const handler = () => {
  870. this._host.window.removeEventListener('keydown', handler);
  871. this._host.document.body.removeEventListener('click', handler);
  872. this._host.document.body.classList.remove('about');
  873. };
  874. this._host.window.addEventListener('keydown', handler);
  875. this._host.document.body.addEventListener('click', handler);
  876. this._host.document.body.classList.add('about');
  877. }
  878. };
  879. view.Menu = class {
  880. constructor(host) {
  881. this.items = [];
  882. this._darwin = host.environment('platform') === 'darwin';
  883. this._document = host.document;
  884. this._stack = [];
  885. this._root = [];
  886. this._buttons = [];
  887. this._accelerators = new Map();
  888. this._keyCodes = new Map([
  889. ['Backspace', 0x08], ['Enter', 0x0D], ['Escape', 0x1B],
  890. ['Left', 0x25], ['Up', 0x26], ['Right', 0x27], ['Down', 0x28],
  891. ['F5', 0x74], ['F11', 0x7a]
  892. ]);
  893. this._symbols = new Map([
  894. ['Backspace', '&#x232B;'], ['Enter', '&#x23ce;'],
  895. ['Up', '&#x2191;'], ['Down', '&#x2193;'],
  896. ]);
  897. this._keydown = (e) => {
  898. this._alt = false;
  899. const code = e.keyCode | (e.altKey ? 0x0200 : 0) | (e.shiftKey ? 0x0100 : 0);
  900. const modifier = (e.ctrlKey ? 0x0400 : 0) | (e.metaKey ? 0x0800 : 0);
  901. if ((code | modifier) === 0x0212) { // Alt
  902. this._alt = true;
  903. } else {
  904. const action =
  905. this._accelerators.get(code | modifier) ||
  906. this._accelerators.get(code | ((e.ctrlKey && !this._darwin) || (e.metaKey && this._darwin) ? 0x1000 : 0));
  907. if (action && this._execute(action)) {
  908. e.preventDefault();
  909. } else {
  910. const item = this._mnemonic(code | modifier);
  911. if (item && this._activate(item)) {
  912. e.preventDefault();
  913. }
  914. }
  915. }
  916. };
  917. this._keyup = (e) => {
  918. if (e.keyCode === 0x0012 && this._alt) { // Alt
  919. if (this._stack.length === 0) {
  920. if (this.open()) {
  921. e.preventDefault();
  922. }
  923. } else if (this._stack.length === 1) {
  924. if (this.close()) {
  925. e.preventDefault();
  926. }
  927. } else {
  928. this._stack = [this];
  929. if (this._root.length > 1) {
  930. this._root = [this];
  931. this._rebuild();
  932. }
  933. this._update();
  934. e.preventDefault();
  935. }
  936. }
  937. this._alt = false;
  938. };
  939. this._next = () => {
  940. const button = this._element.ownerDocument.activeElement;
  941. const index = this._buttons.indexOf(button);
  942. if (index !== -1 && index < this._buttons.length - 1) {
  943. const next = this._buttons[index + 1];
  944. next.focus();
  945. }
  946. };
  947. this._previous = () => {
  948. const button = this._element.ownerDocument.activeElement;
  949. const index = this._buttons.indexOf(button);
  950. if (index > 0) {
  951. const next = this._buttons[index - 1];
  952. next.focus();
  953. }
  954. };
  955. this._push = () => {
  956. const button = this._element.ownerDocument.activeElement;
  957. if (button && button.getAttribute('data-type') === 'group') {
  958. button.click();
  959. }
  960. };
  961. this._pop = () => {
  962. if (this._stack.length > 1) {
  963. this._deactivate();
  964. }
  965. };
  966. this._exit = () => {
  967. this._deactivate();
  968. if (this._stack.length === 0) {
  969. this.close();
  970. }
  971. };
  972. host.window.addEventListener('keydown', this._keydown);
  973. host.window.addEventListener('keyup', this._keyup);
  974. }
  975. attach(element, button) {
  976. this._element = element;
  977. button.addEventListener('click', (e) => {
  978. this.toggle();
  979. e.preventDefault();
  980. });
  981. }
  982. add(value) {
  983. const item = new view.Menu.Command(value);
  984. this.register(item, item.accelerator);
  985. }
  986. group(label) {
  987. const item = new view.Menu.Group(this, label);
  988. item.identifier = `menu-item-${this.items.length}`;
  989. this.items.push(item);
  990. item.shortcut = this.register(item.accelerator);
  991. return item;
  992. }
  993. toggle() {
  994. if (this._element.style.opacity >= 1) {
  995. this.close();
  996. } else {
  997. this._root = [this];
  998. this._stack = [this];
  999. this.open();
  1000. }
  1001. }
  1002. open() {
  1003. if (this._element) {
  1004. if (this._stack.length === 0) {
  1005. this.toggle();
  1006. this._stack = [this];
  1007. }
  1008. this._rebuild();
  1009. this._update();
  1010. this.register(this._exit, 'Escape');
  1011. this.register(this._previous, 'Up');
  1012. this.register(this._next, 'Down');
  1013. this.register(this._pop, 'Left');
  1014. this.register(this._push, 'Right');
  1015. }
  1016. }
  1017. close() {
  1018. if (this._element) {
  1019. this.unregister(this._exit);
  1020. this.unregister(this._previous);
  1021. this.unregister(this._next);
  1022. this.unregister(this._pop);
  1023. this.unregister(this._push);
  1024. this._element.style.opacity = 0;
  1025. this._element.style.left = '-17em';
  1026. const button = this._element.ownerDocument.activeElement;
  1027. if (this._buttons.indexOf(button) > 0) {
  1028. button.blur();
  1029. }
  1030. while (this._root.length > 1) {
  1031. this._deactivate();
  1032. }
  1033. this._stack = [];
  1034. }
  1035. }
  1036. register(action, accelerator) {
  1037. let shortcut = '';
  1038. if (accelerator) {
  1039. let shift = false;
  1040. let alt = false;
  1041. let ctrl = false;
  1042. let cmd = false;
  1043. let cmdOrCtrl = false;
  1044. let key = '';
  1045. for (const part of accelerator.split('+')) {
  1046. switch (part) {
  1047. case 'CmdOrCtrl': cmdOrCtrl = true; break;
  1048. case 'Cmd': cmd = true; break;
  1049. case 'Ctrl': ctrl = true; break;
  1050. case 'Alt': alt = true; break;
  1051. case 'Shift': shift = true; break;
  1052. default: key = part; break;
  1053. }
  1054. }
  1055. if (key !== '') {
  1056. if (this._darwin) {
  1057. shortcut += ctrl ? '&#x2303' : '';
  1058. shortcut += alt ? '&#x2325;' : '';
  1059. shortcut += shift ? '&#x21e7;' : '';
  1060. shortcut += cmdOrCtrl || cmd ? '&#x2318;' : '';
  1061. shortcut += this._symbols.has(key) ? this._symbols.get(key) : key;
  1062. } else {
  1063. shortcut += cmdOrCtrl || ctrl ? 'Ctrl+' : '';
  1064. shortcut += alt ? 'Alt+' : '';
  1065. shortcut += shift ? 'Shift+' : '';
  1066. shortcut += key;
  1067. }
  1068. let code = (cmdOrCtrl ? 0x1000 : 0) | (cmd ? 0x0800 : 0) | (ctrl ? 0x0400 : 0) | (alt ? 0x0200 : 0) | (shift ? 0x0100 : 0);
  1069. code |= this._keyCodes.has(key) ? this._keyCodes.get(key) : key.charCodeAt(0);
  1070. this._accelerators.set(code, action);
  1071. }
  1072. }
  1073. return shortcut;
  1074. }
  1075. unregister(action) {
  1076. this._accelerators = new Map(Array.from(this._accelerators.entries()).filter(([, value]) => value !== action));
  1077. }
  1078. _execute(action) {
  1079. if (typeof action === 'function') {
  1080. action();
  1081. return true;
  1082. }
  1083. switch (action ? action.type : null) {
  1084. case 'group': {
  1085. while (this._stack.length > this._root.length) {
  1086. this._stack.pop();
  1087. }
  1088. this._root.push({ items: [action] });
  1089. this._stack.push(action);
  1090. this._rebuild();
  1091. this._update();
  1092. return true;
  1093. }
  1094. case 'command': {
  1095. this.close();
  1096. setTimeout(() => action.execute(), 10);
  1097. return true;
  1098. }
  1099. default: {
  1100. return false;
  1101. }
  1102. }
  1103. }
  1104. _mnemonic(code) {
  1105. const key = /[a-zA-Z0-9]/.test(String.fromCharCode(code & 0x00FF));
  1106. const modifier = (code & 0xFF00) !== 0;
  1107. const alt = (code & 0xFF00) === 0x0200;
  1108. if (alt && key) {
  1109. this.open();
  1110. }
  1111. if (this._stack.length > 0 && key && (alt || !modifier)) {
  1112. const key = String.fromCharCode(code & 0x00FF);
  1113. const group = this._stack.length > 0 ? this._stack[this._stack.length - 1] : this;
  1114. const item = group.items.find((item) => key === item.mnemonic && (item.type === 'group' || item.type === 'command') && item.enabled);
  1115. if (item) {
  1116. return item;
  1117. }
  1118. }
  1119. return null;
  1120. }
  1121. _activate(item) {
  1122. switch (item ? item.type : null) {
  1123. case 'group': {
  1124. this._stack.push(item);
  1125. this._rebuild();
  1126. this._update();
  1127. return true;
  1128. }
  1129. case 'command': {
  1130. return this._execute(item);
  1131. }
  1132. default: {
  1133. return false;
  1134. }
  1135. }
  1136. }
  1137. _deactivate() {
  1138. if (this._root.length > 1) {
  1139. this._root.pop();
  1140. const group = this._stack.pop();
  1141. this._rebuild();
  1142. this._update();
  1143. if (group) {
  1144. const button = this._buttons.find((button) => button.getAttribute('id') === group.identifier);
  1145. if (button) {
  1146. button.focus();
  1147. }
  1148. }
  1149. } else if (this._stack.length > 0) {
  1150. this._stack.pop();
  1151. this._update();
  1152. }
  1153. }
  1154. _label(item, mnemonic) {
  1155. delete item.mnemonic;
  1156. const value = item.label;
  1157. if (value) {
  1158. const index = value.indexOf('&');
  1159. if (index !== -1) {
  1160. if (mnemonic) {
  1161. item.mnemonic = value[index + 1].toUpperCase();
  1162. return `${value.substring(0, index)}<u>${value[index + 1]}</u>${value.substring(index + 2)}`;
  1163. }
  1164. return value.substring(0, index) + value.substring(index + 1);
  1165. }
  1166. }
  1167. return value || '';
  1168. }
  1169. _rebuild() {
  1170. this._element.replaceChildren();
  1171. const root = this._root[this._root.length - 1];
  1172. for (const group of root.items) {
  1173. const container = this._document.createElement('div');
  1174. container.setAttribute('id', group.identifier);
  1175. container.setAttribute('class', 'menu-group');
  1176. container.innerHTML = "<div class='menu-group-header'></div>";
  1177. for (const item of group.items) {
  1178. switch (item.type) {
  1179. case 'group':
  1180. case 'command': {
  1181. const button = this._document.createElement('button');
  1182. button.setAttribute('class', 'menu-command');
  1183. button.setAttribute('id', item.identifier);
  1184. button.setAttribute('data-type', item.type);
  1185. button.addEventListener('mouseenter', () => button.focus());
  1186. button.addEventListener('click', () => this._execute(item));
  1187. const accelerator = this._document.createElement('span');
  1188. accelerator.setAttribute('class', 'menu-shortcut');
  1189. if (item.type === 'group') {
  1190. accelerator.innerHTML = '&#10095;';
  1191. } else if (item.shortcut) {
  1192. accelerator.innerHTML = item.shortcut;
  1193. }
  1194. button.appendChild(accelerator);
  1195. const content = this._document.createElement('span');
  1196. content.setAttribute('class', 'menu-label');
  1197. button.appendChild(content);
  1198. container.appendChild(button);
  1199. break;
  1200. }
  1201. case 'separator': {
  1202. const element = this._document.createElement('div');
  1203. element.setAttribute('class', 'menu-separator');
  1204. element.setAttribute('id', item.identifier);
  1205. container.appendChild(element);
  1206. break;
  1207. }
  1208. default: {
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. this._element.appendChild(container);
  1214. }
  1215. this._element.style.opacity = 1.0;
  1216. this._element.style.left = '0px';
  1217. if (this._root.length > 1) {
  1218. this._element.style.width = 'auto';
  1219. this._element.style.maxWidth = '60%';
  1220. } else {
  1221. this._element.style.removeProperty('width');
  1222. this._element.style.maxWidth = 'auto';
  1223. }
  1224. }
  1225. _update() {
  1226. this._buttons = [];
  1227. const selected = this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
  1228. const root = this._root[this._root.length - 1];
  1229. for (const group of root.items) {
  1230. let visible = false;
  1231. let block = false;
  1232. const active = this._stack.length <= 1 || this._stack[1] === group;
  1233. const container = this._document.getElementById(group.identifier);
  1234. container.childNodes[0].innerHTML = this._label(group, this === selected);
  1235. for (const item of group.items) {
  1236. switch (item.type) {
  1237. case 'group':
  1238. case 'command': {
  1239. const label = this._label(item, group === selected);
  1240. const button = this._document.getElementById(item.identifier);
  1241. button.childNodes[1].innerHTML = label;
  1242. if (item.enabled) {
  1243. button.removeAttribute('disabled');
  1244. button.style.display = 'block';
  1245. visible = true;
  1246. block = true;
  1247. if (active) {
  1248. this._buttons.push(button);
  1249. }
  1250. } else {
  1251. button.setAttribute('disabled', '');
  1252. button.style.display = 'none';
  1253. }
  1254. break;
  1255. }
  1256. case 'separator': {
  1257. const element = this._document.getElementById(item.identifier);
  1258. element.style.display = block ? 'block' : 'none';
  1259. block = false;
  1260. break;
  1261. }
  1262. default: {
  1263. break;
  1264. }
  1265. }
  1266. }
  1267. for (let i = group.items.length - 1; i >= 0; i--) {
  1268. const item = group.items[i];
  1269. if ((item.type === 'group' || item.type === 'command') && item.enabled) {
  1270. break;
  1271. } else if (item.type === 'separator') {
  1272. const element = this._document.getElementById(item.identifier);
  1273. element.style.display = 'none';
  1274. }
  1275. }
  1276. if (!visible) {
  1277. container.style.display = 'none';
  1278. }
  1279. container.style.opacity = active ? 1 : 0;
  1280. }
  1281. const button = this._element.ownerDocument.activeElement;
  1282. const index = this._buttons.indexOf(button);
  1283. if (index === -1 && this._buttons.length > 0) {
  1284. this._buttons[0].focus();
  1285. }
  1286. }
  1287. };
  1288. view.Menu.Group = class {
  1289. constructor(parent, label) {
  1290. this.type = 'group';
  1291. this.parent = parent;
  1292. this.label = label;
  1293. this.items = [];
  1294. }
  1295. get enabled() {
  1296. return this.items.some((item) => item.enabled);
  1297. }
  1298. add(value) {
  1299. const item = Object.keys(value).length > 0 ? new view.Menu.Command(value) : new view.Menu.Separator();
  1300. item.identifier = `${this.identifier}-${this.items.length}`;
  1301. this.items.push(item);
  1302. item.shortcut = this.parent.register(item, item.accelerator);
  1303. }
  1304. group(label) {
  1305. const item = new view.Menu.Group(this, label);
  1306. item.identifier = `${this.identifier}-${this.items.length}`;
  1307. this.items.push(item);
  1308. item.shortcut = this.parent.register(item, item.accelerator);
  1309. return item;
  1310. }
  1311. clear() {
  1312. for (const item of this.items) {
  1313. if (item.clear) {
  1314. item.clear();
  1315. }
  1316. this.parent.unregister(item);
  1317. }
  1318. this.items = [];
  1319. }
  1320. register(item, accelerator) {
  1321. return this.parent.register(item, accelerator);
  1322. }
  1323. unregister(item) {
  1324. this.parent.unregister(item);
  1325. }
  1326. };
  1327. view.Menu.Command = class {
  1328. constructor(item) {
  1329. this.type = 'command';
  1330. this.accelerator = item.accelerator;
  1331. this._label = item.label;
  1332. this._enabled = item.enabled;
  1333. this._execute = item.execute;
  1334. }
  1335. get label() {
  1336. return typeof this._label === 'function' ? this._label() : this._label;
  1337. }
  1338. get enabled() {
  1339. return this._enabled ? this._enabled() : true;
  1340. }
  1341. execute() {
  1342. if (this._execute && this.enabled) {
  1343. this._execute();
  1344. }
  1345. }
  1346. };
  1347. view.Menu.Separator = class {
  1348. constructor() {
  1349. this.type = 'separator';
  1350. this.enabled = false;
  1351. }
  1352. };
  1353. view.Worker = class {
  1354. constructor(host) {
  1355. this._host = host;
  1356. this._timeout = -1;
  1357. this._create();
  1358. }
  1359. async request(message, delay, notification) {
  1360. if (this._resolve) {
  1361. const resolve = this._resolve;
  1362. resolve({ type: 'terminate' });
  1363. delete this._resolve;
  1364. delete this._reject;
  1365. this._cancel(true);
  1366. } else {
  1367. this._cancel(false);
  1368. }
  1369. return new Promise((resolve, reject) => {
  1370. this._resolve = resolve;
  1371. this._reject = reject;
  1372. this._create();
  1373. this._worker.postMessage(message);
  1374. this._timeout = setTimeout(async () => {
  1375. await this._host.message(notification, null, 'Cancel');
  1376. this._cancel(true);
  1377. delete this._resolve;
  1378. delete this._reject;
  1379. resolve({ type: 'cancel' });
  1380. }, delay);
  1381. });
  1382. }
  1383. _create() {
  1384. if (!this._worker) {
  1385. this._worker = this._host.worker('./worker');
  1386. this._worker.addEventListener('message', (e) => {
  1387. this._cancel(false);
  1388. const message = e.data;
  1389. const resolve = this._resolve;
  1390. const reject = this._reject;
  1391. delete this._resolve;
  1392. delete this._reject;
  1393. if (reject && message.type === 'error') {
  1394. const error = new Error(`Worker: ${message.message}`);
  1395. reject(error);
  1396. } else if (resolve) {
  1397. resolve(message);
  1398. }
  1399. });
  1400. this._worker.addEventListener('error', (e) => {
  1401. this._cancel(true);
  1402. const reject = this._reject;
  1403. delete this._resolve;
  1404. delete this._reject;
  1405. if (reject) {
  1406. reject(new Error(`Unknown worker error type '${e.type}'.`));
  1407. }
  1408. });
  1409. }
  1410. }
  1411. _cancel(terminate) {
  1412. terminate = terminate || this._host.type === 'Test';
  1413. if (this._worker && terminate) {
  1414. this._worker.terminate();
  1415. this._worker = null;
  1416. }
  1417. if (this._timeout !== -1) {
  1418. clearTimeout(this._timeout);
  1419. this._timeout = -1;
  1420. this._host.message();
  1421. }
  1422. }
  1423. };
  1424. view.Graph = class extends grapher.Graph {
  1425. constructor(view, compound) {
  1426. super(compound);
  1427. this.view = view;
  1428. this.counter = 0;
  1429. this._nodeKey = 0;
  1430. this._values = new Map();
  1431. this._tensors = new Map();
  1432. this._table = new Map();
  1433. this._selection = new Set();
  1434. this._zoom = 1;
  1435. }
  1436. get model() {
  1437. return this.view.model;
  1438. }
  1439. get host() {
  1440. return this.view.host;
  1441. }
  1442. get options() {
  1443. return this.view.options;
  1444. }
  1445. createNode(node) {
  1446. const obj = new view.Node(this, node);
  1447. obj.name = (this._nodeKey++).toString();
  1448. this._table.set(node, obj);
  1449. return obj;
  1450. }
  1451. createGraph(graph) {
  1452. const obj = new view.Node(this, graph, 'graph');
  1453. obj.name = (this._nodeKey++).toString();
  1454. this._table.set(graph, obj);
  1455. return obj;
  1456. }
  1457. createInput(input) {
  1458. const obj = new view.Input(this, input);
  1459. obj.name = (this._nodeKey++).toString();
  1460. this._table.set(input, obj);
  1461. return obj;
  1462. }
  1463. createOutput(output) {
  1464. const obj = new view.Output(this, output);
  1465. obj.name = (this._nodeKey++).toString();
  1466. this._table.set(output, obj);
  1467. return obj;
  1468. }
  1469. createValue(value) {
  1470. const key = value && value.name && !value.initializer ? value.name : value;
  1471. if (this._values.has(key)) {
  1472. // duplicate argument name
  1473. const obj = this._values.get(key);
  1474. this._table.set(value, obj);
  1475. } else {
  1476. const obj = new view.Value(this, value);
  1477. this._values.set(key, obj);
  1478. this._table.set(value, obj);
  1479. }
  1480. return this._values.get(key);
  1481. }
  1482. createArgument(value) {
  1483. if (Array.isArray(value.value) && value.value.length === 1 && value.value[0].initializer) {
  1484. if (!this._tensors.has(value)) {
  1485. const obj = new view.Argument(this, value);
  1486. this._tensors.set(value, obj);
  1487. this._table.set(value, obj);
  1488. }
  1489. return this._tensors.get(value);
  1490. }
  1491. return null;
  1492. }
  1493. add(graph, signature) {
  1494. this.identifier = this.model.identifier;
  1495. this.identifier += graph && graph.name ? `.${graph.name.replace(/\/|\\/g, '.')}` : '';
  1496. const clusters = new Set();
  1497. const clusterParentMap = new Map();
  1498. const groups = graph.groups;
  1499. if (groups) {
  1500. for (const node of graph.nodes) {
  1501. if (node.group) {
  1502. const path = node.group.split('/');
  1503. while (path.length > 0) {
  1504. const name = path.join('/');
  1505. path.pop();
  1506. clusterParentMap.set(name, path.join('/'));
  1507. }
  1508. }
  1509. }
  1510. }
  1511. const inputs = signature ? signature.inputs : graph.inputs;
  1512. const outputs = signature ? signature.outputs : graph.outputs;
  1513. if (Array.isArray(inputs)) {
  1514. for (const argument of inputs) {
  1515. if (argument.visible !== false) {
  1516. const viewInput = this.createInput(argument);
  1517. this.setNode(viewInput);
  1518. for (const value of argument.value) {
  1519. this.createValue(value).from = viewInput;
  1520. }
  1521. }
  1522. }
  1523. }
  1524. for (const node of graph.nodes) {
  1525. const viewNode = this.createNode(node);
  1526. this.setNode(viewNode);
  1527. let outputs = node.outputs;
  1528. if (node.chain && node.chain.length > 0) {
  1529. const chainOutputs = node.chain[node.chain.length - 1].outputs;
  1530. if (chainOutputs.length > 0) {
  1531. outputs = chainOutputs;
  1532. }
  1533. }
  1534. if (Array.isArray(outputs)) {
  1535. for (const argument of outputs) {
  1536. for (const value of argument.value) {
  1537. if (!value) {
  1538. throw new view.Error('Invalid null argument.');
  1539. }
  1540. if (value.name !== '') {
  1541. this.createValue(value).from = viewNode;
  1542. }
  1543. }
  1544. }
  1545. }
  1546. if (Array.isArray(node.controlDependencies) && node.controlDependencies.length > 0) {
  1547. for (const value of node.controlDependencies) {
  1548. this.createValue(value).controlDependency(viewNode);
  1549. }
  1550. }
  1551. const createCluster = (name) => {
  1552. if (!clusters.has(name)) {
  1553. this.setNode({ name, rx: 5, ry: 5 });
  1554. clusters.add(name);
  1555. const parent = clusterParentMap.get(name);
  1556. if (parent) {
  1557. createCluster(parent);
  1558. this.setParent(name, parent);
  1559. }
  1560. }
  1561. };
  1562. if (groups) {
  1563. let groupName = node.group;
  1564. if (groupName && groupName.length > 0) {
  1565. if (!clusterParentMap.has(groupName)) {
  1566. const lastIndex = groupName.lastIndexOf('/');
  1567. if (lastIndex === -1) {
  1568. groupName = null;
  1569. } else {
  1570. groupName = groupName.substring(0, lastIndex);
  1571. if (!clusterParentMap.has(groupName)) {
  1572. groupName = null;
  1573. }
  1574. }
  1575. }
  1576. if (groupName) {
  1577. createCluster(`${groupName}\ngroup`);
  1578. this.setParent(viewNode.name, `${groupName}\ngroup`);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. if (Array.isArray(outputs)) {
  1584. for (const argument of outputs) {
  1585. if (argument.visible !== false) {
  1586. const viewOutput = this.createOutput(argument);
  1587. this.setNode(viewOutput);
  1588. if (Array.isArray(argument.value)) {
  1589. for (const value of argument.value) {
  1590. this.createValue(value).to.push(viewOutput);
  1591. }
  1592. }
  1593. }
  1594. }
  1595. }
  1596. }
  1597. build(document) {
  1598. const element = document.getElementById('target');
  1599. while (element.lastChild) {
  1600. element.removeChild(element.lastChild);
  1601. }
  1602. const canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  1603. canvas.setAttribute('id', 'canvas');
  1604. canvas.setAttribute('class', 'canvas');
  1605. canvas.setAttribute('preserveAspectRatio', 'xMidYMid meet');
  1606. canvas.setAttribute('width', '100%');
  1607. canvas.setAttribute('height', '100%');
  1608. element.appendChild(canvas);
  1609. // Workaround for Safari background drag/zoom issue:
  1610. // https://stackoverflow.com/questions/40887193/d3-js-zoom-is-not-working-with-mousewheel-in-safari
  1611. const background = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
  1612. background.setAttribute('id', 'background');
  1613. background.setAttribute('fill', 'none');
  1614. background.setAttribute('pointer-events', 'all');
  1615. canvas.appendChild(background);
  1616. const origin = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  1617. origin.setAttribute('id', 'origin');
  1618. canvas.appendChild(origin);
  1619. for (const value of this._values.values()) {
  1620. value.build();
  1621. }
  1622. super.build(document);
  1623. }
  1624. async measure() {
  1625. const document = this.host.document;
  1626. const window = this.host.window;
  1627. if (document.fonts && document.fonts.ready) {
  1628. try {
  1629. await document.fonts.ready;
  1630. } catch {
  1631. // continue regardless of error
  1632. }
  1633. }
  1634. await new Promise((resolve) => {
  1635. window.requestAnimationFrame(() => {
  1636. window.requestAnimationFrame(() => {
  1637. window.requestAnimationFrame(resolve);
  1638. });
  1639. });
  1640. });
  1641. await super.measure();
  1642. }
  1643. select(selection) {
  1644. if (this._selection.size > 0) {
  1645. for (const element of this._selection) {
  1646. element.deselect();
  1647. }
  1648. this._selection.clear();
  1649. }
  1650. if (selection) {
  1651. let array = [];
  1652. for (const value of selection) {
  1653. if (this._table.has(value)) {
  1654. const element = this._table.get(value);
  1655. array = array.concat(element.select());
  1656. this._selection.add(element);
  1657. }
  1658. }
  1659. return array;
  1660. }
  1661. return null;
  1662. }
  1663. activate(value) {
  1664. if (this._table.has(value)) {
  1665. this.select(null);
  1666. const element = this._table.get(value);
  1667. element.activate();
  1668. return this.select([value]);
  1669. }
  1670. return [];
  1671. }
  1672. focus(selection) {
  1673. for (const value of selection) {
  1674. const element = this._table.get(value);
  1675. if (element && !this._selection.has(element)) {
  1676. element.select();
  1677. }
  1678. }
  1679. }
  1680. blur(selection) {
  1681. for (const value of selection) {
  1682. const element = this._table.get(value);
  1683. if (element && !this._selection.has(element)) {
  1684. element.deselect();
  1685. }
  1686. }
  1687. }
  1688. restore(state) {
  1689. const document = this.host.document;
  1690. const canvas = document.getElementById('canvas');
  1691. const origin = document.getElementById('origin');
  1692. const background = document.getElementById('background');
  1693. const elements = Array.from(canvas.getElementsByClassName('graph-input') || []);
  1694. if (elements.length === 0) {
  1695. const nodeElements = Array.from(canvas.getElementsByClassName('graph-node') || []);
  1696. if (nodeElements.length > 0) {
  1697. elements.push(nodeElements[0]);
  1698. }
  1699. }
  1700. const size = canvas.getBBox();
  1701. const margin = 100;
  1702. const width = Math.ceil(margin + size.width + margin);
  1703. const height = Math.ceil(margin + size.height + margin);
  1704. origin.setAttribute('transform', `translate(${margin - size.x}, ${margin - size.y}) scale(1)`);
  1705. background.setAttribute('width', width);
  1706. background.setAttribute('height', height);
  1707. this._width = width;
  1708. this._height = height;
  1709. delete this._scrollLeft;
  1710. delete this._scrollRight;
  1711. canvas.setAttribute('viewBox', `0 0 ${width} ${height}`);
  1712. canvas.setAttribute('width', width);
  1713. canvas.setAttribute('height', height);
  1714. this._zoom = state ? state.zoom : 1;
  1715. this._updateZoom(this._zoom);
  1716. const container = document.getElementById('target');
  1717. const context = state ? this.select([state.context]) : [];
  1718. if (context.length > 0) {
  1719. this.scrollTo(context, 'instant');
  1720. } else if (elements && elements.length > 0) {
  1721. // Center view based on input elements
  1722. const bounds = container.getBoundingClientRect();
  1723. const xs = [];
  1724. const ys = [];
  1725. for (let i = 0; i < elements.length; i++) {
  1726. const element = elements[i];
  1727. const rect = element.getBoundingClientRect();
  1728. const width = Math.min(rect.width, bounds.width);
  1729. const height = Math.min(rect.width, bounds.width);
  1730. xs.push(rect.left + (width / 2));
  1731. ys.push(rect.top + (height / 2));
  1732. }
  1733. let [x] = xs;
  1734. const [y] = ys;
  1735. if (ys.every((y) => y === ys[0])) {
  1736. x = xs.reduce((a, b) => a + b, 0) / xs.length;
  1737. }
  1738. const left = (container.scrollLeft + x - bounds.left) - (bounds.width / 2);
  1739. const top = (container.scrollTop + y - bounds.top) - (bounds.height / 2);
  1740. container.scrollTo({ left, top, behavior: 'auto' });
  1741. } else {
  1742. const canvasRect = canvas.getBoundingClientRect();
  1743. const graphRect = container.getBoundingClientRect();
  1744. const left = (container.scrollLeft + (canvasRect.width / 2) - graphRect.left) - (graphRect.width / 2);
  1745. const top = (container.scrollTop + (canvasRect.height / 2) - graphRect.top) - (graphRect.height / 2);
  1746. container.scrollTo({ left, top, behavior: 'auto' });
  1747. }
  1748. }
  1749. register() {
  1750. if (!this._events) {
  1751. this._events = {};
  1752. this._events.scroll = (e) => this._scrollHandler(e);
  1753. this._events.wheel = (e) => this._wheelHandler(e);
  1754. this._events.gesturestart = (e) => this._gestureStartHandler(e);
  1755. this._events.pointerdown = (e) => this._pointerDownHandler(e);
  1756. this._events.touchstart = (e) => this._touchStartHandler(e);
  1757. const document = this.host.document;
  1758. const element = document.getElementById('target');
  1759. element.focus();
  1760. element.addEventListener('scroll', this._events.scroll);
  1761. element.addEventListener('wheel', this._events.wheel, { passive: false });
  1762. element.addEventListener('pointerdown', this._events.pointerdown);
  1763. if (this.host.environment('agent') === 'safari') {
  1764. element.addEventListener('gesturestart', this._events.gesturestart, false);
  1765. } else {
  1766. element.addEventListener('touchstart', this._events.touchstart, { passive: true });
  1767. }
  1768. }
  1769. }
  1770. unregister() {
  1771. if (this._events) {
  1772. const document = this.host.document;
  1773. const element = document.getElementById('target');
  1774. element.removeEventListener('scroll', this._events.scroll);
  1775. element.removeEventListener('wheel', this._events.wheel);
  1776. element.removeEventListener('pointerdown', this._events.pointerdown);
  1777. element.removeEventListener('gesturestart', this._events.gesturestart);
  1778. element.removeEventListener('touchstart', this._events.touchstart);
  1779. delete this._events;
  1780. }
  1781. }
  1782. get zoom() {
  1783. return this._zoom;
  1784. }
  1785. set zoom(value) {
  1786. this._updateZoom(value);
  1787. }
  1788. _updateZoom(zoom, e) {
  1789. const document = this.host.document;
  1790. const container = document.getElementById('target');
  1791. const canvas = document.getElementById('canvas');
  1792. const limit = this.view.options.direction === 'vertical' ?
  1793. container.clientHeight / this._height :
  1794. container.clientWidth / this._width;
  1795. const min = Math.min(Math.max(limit, 0.15), 1);
  1796. zoom = Math.max(min, Math.min(zoom, 1.4));
  1797. const scrollLeft = this._scrollLeft || container.scrollLeft;
  1798. const scrollTop = this._scrollTop || container.scrollTop;
  1799. const x = (e ? e.pageX : (container.clientWidth / 2)) + scrollLeft;
  1800. const y = (e ? e.pageY : (container.clientHeight / 2)) + scrollTop;
  1801. const width = zoom * this._width;
  1802. const height = zoom * this._height;
  1803. canvas.style.width = `${width}px`;
  1804. canvas.style.height = `${height}px`;
  1805. this._scrollLeft = Math.max(0, ((x * zoom) / this._zoom) - (x - scrollLeft));
  1806. this._scrollTop = Math.max(0, ((y * zoom) / this._zoom) - (y - scrollTop));
  1807. container.scrollLeft = this._scrollLeft;
  1808. container.scrollTop = this._scrollTop;
  1809. this._zoom = zoom;
  1810. }
  1811. _pointerDownHandler(e) {
  1812. if (e.pointerType === 'touch' || e.buttons !== 1) {
  1813. return;
  1814. }
  1815. // Workaround for Firefox emitting 'pointerdown' event when scrollbar is pressed
  1816. if (e.originalTarget) {
  1817. try {
  1818. /* eslint-disable no-unused-expressions */
  1819. e.originalTarget.id;
  1820. /* eslint-enable no-unused-expressions */
  1821. } catch {
  1822. return;
  1823. }
  1824. }
  1825. const document = this.host.document;
  1826. const container = document.getElementById('target');
  1827. e.target.setPointerCapture(e.pointerId);
  1828. this._mousePosition = {
  1829. left: container.scrollLeft,
  1830. top: container.scrollTop,
  1831. x: e.clientX,
  1832. y: e.clientY
  1833. };
  1834. e.target.style.cursor = 'grabbing';
  1835. e.preventDefault();
  1836. e.stopImmediatePropagation();
  1837. const pointerMoveHandler = (e) => {
  1838. e.preventDefault();
  1839. e.stopImmediatePropagation();
  1840. if (this._mousePosition) {
  1841. const dx = e.clientX - this._mousePosition.x;
  1842. const dy = e.clientY - this._mousePosition.y;
  1843. this._mousePosition.moved = dx * dx + dy * dy > 0;
  1844. if (this._mousePosition.moved) {
  1845. const document = this.host.document;
  1846. const container = document.getElementById('target');
  1847. container.scrollTop = this._mousePosition.top - dy;
  1848. container.scrollLeft = this._mousePosition.left - dx;
  1849. }
  1850. }
  1851. };
  1852. const clickHandler = (e) => {
  1853. e.stopPropagation();
  1854. document.removeEventListener('click', clickHandler, true);
  1855. };
  1856. const pointerUpHandler = (e) => {
  1857. e.target.releasePointerCapture(e.pointerId);
  1858. e.target.style.removeProperty('cursor');
  1859. container.removeEventListener('pointerup', pointerUpHandler);
  1860. container.removeEventListener('pointermove', pointerMoveHandler);
  1861. if (this._mousePosition && this._mousePosition.moved) {
  1862. e.preventDefault();
  1863. e.stopImmediatePropagation();
  1864. delete this._mousePosition;
  1865. document.addEventListener('click', clickHandler, true);
  1866. }
  1867. };
  1868. container.addEventListener('pointermove', pointerMoveHandler);
  1869. container.addEventListener('pointerup', pointerUpHandler);
  1870. }
  1871. _touchStartHandler(e) {
  1872. if (e.touches.length === 2) {
  1873. this._touchPoints = Array.from(e.touches);
  1874. this._touchZoom = this._zoom;
  1875. }
  1876. const touchMoveHandler = (e) => {
  1877. if (Array.isArray(this._touchPoints) && this._touchPoints.length === 2 && e.touches.length === 2) {
  1878. const distance = (points) => {
  1879. const dx = (points[1].clientX - points[0].clientX);
  1880. const dy = (points[1].clientY - points[0].clientY);
  1881. return Math.sqrt(dx * dx + dy * dy);
  1882. };
  1883. const d1 = distance(Array.from(e.touches));
  1884. const d2 = distance(this._touchPoints);
  1885. if (d2 !== 0) {
  1886. const points = this._touchPoints;
  1887. const e = {
  1888. pageX: (points[1].pageX + points[0].pageX) / 2,
  1889. pageY: (points[1].pageY + points[0].pageY) / 2
  1890. };
  1891. const zoom = d2 === 0 ? d1 : d1 / d2;
  1892. this._updateZoom(this._touchZoom * zoom, e);
  1893. }
  1894. }
  1895. };
  1896. const document = this.host.document;
  1897. const container = document.getElementById('target');
  1898. const touchEndHandler = () => {
  1899. container.removeEventListener('touchmove', touchMoveHandler, { passive: true });
  1900. container.removeEventListener('touchcancel', touchEndHandler, { passive: true });
  1901. container.removeEventListener('touchend', touchEndHandler, { passive: true });
  1902. delete this._touchPoints;
  1903. delete this._touchZoom;
  1904. };
  1905. container.addEventListener('touchmove', touchMoveHandler, { passive: true });
  1906. container.addEventListener('touchcancel', touchEndHandler, { passive: true });
  1907. container.addEventListener('touchend', touchEndHandler, { passive: true });
  1908. }
  1909. _gestureStartHandler(e) {
  1910. e.preventDefault();
  1911. this._gestureZoom = this._zoom;
  1912. const document = this.host.document;
  1913. const container = document.getElementById('target');
  1914. const gestureChangeHandler = (e) => {
  1915. e.preventDefault();
  1916. this._updateZoom(this._gestureZoom * e.scale, e);
  1917. };
  1918. const gestureEndHandler = (e) => {
  1919. container.removeEventListener('gesturechange', gestureChangeHandler, false);
  1920. container.removeEventListener('gestureend', gestureEndHandler, false);
  1921. e.preventDefault();
  1922. if (this._gestureZoom) {
  1923. this._updateZoom(this._gestureZoom * e.scale, e);
  1924. delete this._gestureZoom;
  1925. }
  1926. };
  1927. container.addEventListener('gesturechange', gestureChangeHandler, false);
  1928. container.addEventListener('gestureend', gestureEndHandler, false);
  1929. }
  1930. _scrollHandler(e) {
  1931. if (this._scrollLeft && e.target.scrollLeft !== Math.floor(this._scrollLeft)) {
  1932. delete this._scrollLeft;
  1933. }
  1934. if (this._scrollTop && e.target.scrollTop !== Math.floor(this._scrollTop)) {
  1935. delete this._scrollTop;
  1936. }
  1937. }
  1938. _wheelHandler(e) {
  1939. if (e.shiftKey || e.ctrlKey || this.view.options.mousewheel === 'zoom') {
  1940. let factor = 1;
  1941. if (e.deltaMode === 1) {
  1942. factor = 0.05;
  1943. } else if (e.deltaMode) {
  1944. factor = 1;
  1945. } else {
  1946. factor = 0.002;
  1947. }
  1948. const delta = -e.deltaY * factor * (e.ctrlKey ? 10 : 1);
  1949. this._updateZoom(this._zoom * Math.pow(2, delta), e);
  1950. e.preventDefault();
  1951. }
  1952. }
  1953. scrollTo(selection, behavior) {
  1954. if (selection && selection.length > 0) {
  1955. const document = this.host.document;
  1956. const container = document.getElementById('target');
  1957. const rect = container.getBoundingClientRect();
  1958. // Exclude scrollbars
  1959. const cw = container.clientWidth;
  1960. const ch = container.clientHeight;
  1961. // Shrink the test rectangle by 10%
  1962. const bounds = {};
  1963. bounds.left = (rect.x + cw / 2) - (cw * 0.45);
  1964. bounds.width = cw * 0.9;
  1965. bounds.right = bounds.left + bounds.width;
  1966. bounds.top = (rect.y + ch / 2) - (ch * 0.45);
  1967. bounds.height = ch * 0.9;
  1968. bounds.bottom = bounds.top + bounds.height;
  1969. let x = 0;
  1970. let y = 0;
  1971. let left = Number.POSITIVE_INFINITY;
  1972. let right = Number.NEGATIVE_INFINITY;
  1973. let top = Number.POSITIVE_INFINITY;
  1974. let bottom = Number.NEGATIVE_INFINITY;
  1975. for (const element of selection) {
  1976. const rect = element.getBoundingClientRect();
  1977. const width = Math.min(rect.width, bounds.width);
  1978. const height = Math.min(rect.height, bounds.height);
  1979. x += rect.left + (width / 2);
  1980. y += rect.top + (height / 2);
  1981. left = Math.min(left, rect.left);
  1982. right = Math.max(right, rect.right);
  1983. top = Math.min(top, rect.top);
  1984. bottom = Math.max(bottom, rect.bottom);
  1985. }
  1986. // No need to scroll if new selection is in the safe area.
  1987. if (right <= bounds.right && left >= bounds.left && bottom <= bounds.bottom && top >= bounds.top) {
  1988. return;
  1989. }
  1990. // If new selection is completely out of the bounds, scroll to centerize it.
  1991. if (bottom - top >= bounds.height || right - left >= bounds.width || right < rect.left || left > rect.right || bottom < rect.top || top > rect.bottom) {
  1992. x /= selection.length;
  1993. y /= selection.length;
  1994. const options = {};
  1995. options.left = (container.scrollLeft + x - bounds.left) - (bounds.width / 2);
  1996. options.top = (container.scrollTop + y - bounds.top) - (bounds.height / 2);
  1997. options.behavior = behavior || 'smooth';
  1998. container.scrollTo(options);
  1999. return;
  2000. }
  2001. const options = {};
  2002. options.left = 0;
  2003. options.top = 0;
  2004. options.behavior = behavior || 'smooth';
  2005. // similar to scrollIntoView block: "nearest"
  2006. const dr = bounds.right - right;
  2007. const dl = left - bounds.left;
  2008. const db = bounds.bottom - bottom;
  2009. const dt = top - bounds.top;
  2010. if (right - left < bounds.width) {
  2011. if (dl < 0) {
  2012. options.left = dl;
  2013. } else if (dr < 0) {
  2014. options.left = -dr;
  2015. }
  2016. }
  2017. if (bottom - top < bounds.height) {
  2018. if (dt < 0) {
  2019. options.top = dt;
  2020. } else if (db < 0) {
  2021. options.top = -db;
  2022. }
  2023. }
  2024. container.scrollBy(options);
  2025. }
  2026. }
  2027. };
  2028. view.Node = class extends grapher.Node {
  2029. constructor(context, value, type) {
  2030. super();
  2031. this.context = context;
  2032. this.value = value;
  2033. this.id = `node-${value.name ? `name-${value.name}` : `id-${(context.counter++)}`}`;
  2034. this._add(value, type);
  2035. const inputs = value.inputs;
  2036. if (type !== 'graph' && Array.isArray(inputs)) {
  2037. for (const argument of inputs) {
  2038. if (!argument.type || argument.type.endsWith('*')) {
  2039. if (Array.isArray(argument.value) && argument.value.length === 1 && argument.value[0].initializer) {
  2040. context.createArgument(argument);
  2041. } else {
  2042. for (const value of argument.value) {
  2043. if (value === null) {
  2044. // null argument
  2045. } else if (value.name !== '' && !value.initializer) {
  2046. context.createValue(value).to.push(this);
  2047. } else if (value.initializer) {
  2048. context.createValue(value);
  2049. }
  2050. }
  2051. }
  2052. } else if (Array.isArray(argument.value) && argument.value.some((value) => value && value.constructor && value.constructor.name === 'Value' && typeof value.name === 'string' && value.name !== '' && !value.initializer)) {
  2053. for (const value of argument.value) {
  2054. if (value && value.constructor && value.constructor.name === 'Value' && typeof value.name === 'string' && value.name !== '' && !value.initializer) {
  2055. context.createValue(value).to.push(this);
  2056. }
  2057. }
  2058. }
  2059. }
  2060. }
  2061. }
  2062. get class() {
  2063. return 'graph-node';
  2064. }
  2065. get inputs() {
  2066. return this.value.inputs;
  2067. }
  2068. get outputs() {
  2069. return this.value.outputs;
  2070. }
  2071. _add(value, type) {
  2072. const node = type === 'graph' ? { type: value } : value;
  2073. const options = this.context.options;
  2074. const header = this.header();
  2075. const category = node.type && node.type.category ? node.type.category : '';
  2076. if (node.type && typeof node.type.name !== 'string' || !node.type.name.split) { // #416
  2077. const error = new view.Error(`Unsupported node type '${JSON.stringify(node.type.name)}'.`);
  2078. if (this.context.model && this.context.model.identifier) {
  2079. error.context = this.context.model.identifier;
  2080. }
  2081. throw error;
  2082. }
  2083. let content = options.names && (node.name || node.identifier) ? (node.name || node.identifier) : node.type.name.split('.').pop();
  2084. let tooltip = options.names && (node.name || node.identifier) ? `[${node.type.name}]` : (node.name || node.identifier);
  2085. if (content.length > 21) {
  2086. tooltip = options.names ? `${content}` : `[${content}]`;
  2087. const begin = content.substring(0, 10);
  2088. const end = content.substring(content.length - 10, content.length);
  2089. content = `${begin}\u2026${end}`;
  2090. }
  2091. const styles = category ? ['node-item-type', `node-item-type-${category.toLowerCase()}`] : ['node-item-type'];
  2092. const title = header.add(null, styles, content, tooltip);
  2093. title.on('click', () => {
  2094. this.context.activate(value);
  2095. });
  2096. if (node.type.type || (Array.isArray(node.type.nodes) && node.type.nodes.length > 0)) {
  2097. let icon = '\u0192';
  2098. let tooltip = 'Show Function Definition';
  2099. if (type === 'graph') {
  2100. icon = '\u25CB';
  2101. tooltip = 'Show Graph';
  2102. } else if (node.type.type === 'weights') {
  2103. icon = '\u25CF';
  2104. tooltip = 'Show Weights';
  2105. }
  2106. const definition = header.add(null, styles, icon, tooltip);
  2107. definition.on('click', async () => await this.context.view.pushTarget(node.type, this.value));
  2108. }
  2109. if (Array.isArray(node.nodes)) {
  2110. // this._expand = header.add(null, styles, '+', null);
  2111. // this._expand.on('click', () => this.toggle());
  2112. }
  2113. let current = null;
  2114. const list = () => {
  2115. if (!current) {
  2116. current = this.list();
  2117. current.on('click', () => this.context.activate(node));
  2118. }
  2119. return current;
  2120. };
  2121. let hiddenTensors = false;
  2122. const objects = [];
  2123. const attribute = (argument) => {
  2124. let content = new view.Formatter(argument.value, argument.type).toString();
  2125. if (content && content.length > 12) {
  2126. content = `${content.substring(0, 12)}\u2026`;
  2127. }
  2128. const item = list().argument(argument.name, content);
  2129. item.tooltip = argument.type;
  2130. if (!content.startsWith('\u3008')) {
  2131. item.separator = ' = ';
  2132. }
  2133. return item;
  2134. };
  2135. const isObject = (node) => {
  2136. if (node.name || node.identifier || node.description ||
  2137. (Array.isArray(node.inputs) && node.inputs.length > 0) ||
  2138. (Array.isArray(node.outputs) && node.outputs.length > 0) ||
  2139. (Array.isArray(node.attributes) && node.attributes.length > 0) ||
  2140. (Array.isArray(node.chain) && node.chain.length > 0) ||
  2141. (node.type && Array.isArray(node.type.nodes) && node.type.nodes.length > 0)) {
  2142. return true;
  2143. }
  2144. return false;
  2145. };
  2146. const inputs = node.inputs;
  2147. if (Array.isArray(inputs)) {
  2148. for (const argument of inputs) {
  2149. const type = argument.type;
  2150. if (argument.visible !== false &&
  2151. ((type === 'graph') ||
  2152. (type === 'object' && isObject(argument.value)) ||
  2153. (type === 'object[]' || type === 'function' || type === 'function[]'))) {
  2154. objects.push(argument);
  2155. } else if (options.weights && argument.visible !== false && argument.type !== 'attribute' && Array.isArray(argument.value) && argument.value.length === 1 && argument.value[0].initializer) {
  2156. const item = this.context.createArgument(argument);
  2157. list().add(item);
  2158. } else if (options.weights && (argument.visible === false || Array.isArray(argument.value) && argument.value.length > 1) && (!argument.type || argument.type.endsWith('*')) && argument.value.some((value) => value !== null && value.initializer)) {
  2159. hiddenTensors = true;
  2160. } else if (options.attributes && argument.visible !== false && argument.type && !argument.type.endsWith('*')) {
  2161. const item = attribute(argument);
  2162. list().add(item);
  2163. }
  2164. }
  2165. }
  2166. if (Array.isArray(node.attributes)) {
  2167. const attributes = node.attributes.slice();
  2168. attributes.sort((a, b) => a.name.toUpperCase().localeCompare(b.name.toUpperCase()));
  2169. for (const argument of attributes) {
  2170. const type = argument.type;
  2171. if (argument.visible !== false &&
  2172. ((type === 'graph') ||
  2173. (type === 'object') ||
  2174. type === 'object[]' || type === 'function' || type === 'function[]')) {
  2175. objects.push(argument);
  2176. } else if (options.attributes && argument.visible !== false) {
  2177. const item = attribute(argument);
  2178. list().add(item);
  2179. }
  2180. }
  2181. }
  2182. if (hiddenTensors) {
  2183. const item = list().argument('\u3008\u2026\u3009', '');
  2184. list().add(item);
  2185. }
  2186. for (const argument of objects) {
  2187. const type = argument.type;
  2188. let content = null;
  2189. if (type === 'graph') {
  2190. content = this.context.createGraph(argument.value);
  2191. this.context.setNode(content);
  2192. } else if (type === 'graph[]') {
  2193. content = argument.value.map((value) => this.context.createGraph(value));
  2194. } else if (type === 'function' || argument.type === 'object') {
  2195. content = this.context.createNode(argument.value);
  2196. } else if (type === 'function[]' || argument.type === 'object[]') {
  2197. content = argument.value.map((value) => this.context.createNode(value));
  2198. }
  2199. const item = list().argument(argument.name, content);
  2200. list().add(item);
  2201. }
  2202. if (Array.isArray(node.nodes) && node.nodes.length > 0) {
  2203. // this.canvas = this.canvas();
  2204. }
  2205. if (Array.isArray(node.chain) && node.chain.length > 0) {
  2206. for (const innerNode of node.chain) {
  2207. this.context.createNode(innerNode);
  2208. this._add(innerNode);
  2209. }
  2210. }
  2211. if (node.inner) {
  2212. this.context.createNode(node.inner);
  2213. this._add(node.inner);
  2214. }
  2215. }
  2216. toggle() {
  2217. this._expand.content = '-';
  2218. this.context.view.target = new view.Graph(this.context.view, false);
  2219. this.context.view.target.add(this.value);
  2220. // const document = this.element.ownerDocument;
  2221. // const parent = this.element.parentElement;
  2222. // this._target.build(document, parent);
  2223. // this._target.update();
  2224. this.canvas.width = 300;
  2225. this.canvas.height = 300;
  2226. this.layout();
  2227. this.context.update();
  2228. }
  2229. activate() {
  2230. this.context.view.showNodeProperties(this.value);
  2231. }
  2232. edge(to) {
  2233. this._edges = this._edges || new Map();
  2234. if (!this._edges.has(to)) {
  2235. this._edges.set(to, new view.Edge(this, to));
  2236. }
  2237. return this._edges.get(to);
  2238. }
  2239. };
  2240. view.Input = class extends grapher.Node {
  2241. constructor(context, value) {
  2242. super();
  2243. this.context = context;
  2244. this.value = value;
  2245. view.Input.counter = view.Input.counter || 0;
  2246. const types = value.value.map((argument) => argument.type || '').join('\n');
  2247. let name = value.name || '';
  2248. if (name.length > 16) {
  2249. name = name.split('/').pop();
  2250. }
  2251. const header = this.header();
  2252. const title = header.add(null, ['graph-item-input'], name, types);
  2253. title.on('click', () => this.context.view.showTargetProperties());
  2254. this.id = `input-${name ? `name-${name}` : `id-${(view.Input.counter++)}`}`;
  2255. }
  2256. get class() {
  2257. return 'graph-input';
  2258. }
  2259. get inputs() {
  2260. return [];
  2261. }
  2262. get outputs() {
  2263. return [this.value];
  2264. }
  2265. activate() {
  2266. this.context.view.showTargetProperties();
  2267. }
  2268. edge(to) {
  2269. this._edges = this._edges || new Map();
  2270. if (!this._edges.has(to)) {
  2271. this._edges.set(to, new view.Edge(this, to));
  2272. }
  2273. return this._edges.get(to);
  2274. }
  2275. };
  2276. view.Output = class extends grapher.Node {
  2277. constructor(context, value) {
  2278. super();
  2279. this.context = context;
  2280. this.value = value;
  2281. if (Array.isArray(value.value)) {
  2282. const types = value.value.map((argument) => argument.type || '').join('\n');
  2283. let name = value.name || '';
  2284. if (name.length > 16) {
  2285. name = name.split('/').pop();
  2286. }
  2287. const header = this.header();
  2288. const title = header.add(null, ['graph-item-output'], name, types);
  2289. title.on('click', () => this.context.view.showTargetProperties());
  2290. }
  2291. }
  2292. get inputs() {
  2293. return [this.value];
  2294. }
  2295. get outputs() {
  2296. return [];
  2297. }
  2298. activate() {
  2299. this.context.view.showTargetProperties();
  2300. }
  2301. };
  2302. view.Value = class {
  2303. constructor(context, value) {
  2304. this.context = context;
  2305. this.value = value;
  2306. this.from = null;
  2307. this.to = [];
  2308. }
  2309. controlDependency(node) {
  2310. this._controlDependencies = this._controlDependencies || new Set();
  2311. this._controlDependencies.add(this.to.length);
  2312. this.to.push(node);
  2313. }
  2314. build() {
  2315. this._edges = this._edges || [];
  2316. if (this.from && Array.isArray(this.to)) {
  2317. for (let i = 0; i < this.to.length; i++) {
  2318. const to = this.to[i];
  2319. let content = '';
  2320. const type = this.value.type;
  2321. if (type &&
  2322. type.shape &&
  2323. type.shape.dimensions &&
  2324. type.shape.dimensions.length > 0 &&
  2325. type.shape.dimensions.every((dim) => !dim || Number.isInteger(dim) || typeof dim === 'bigint' || (typeof dim === 'string'))) {
  2326. content = type.shape.dimensions.map((dim) => (dim !== null && dim !== undefined && dim !== -1) ? dim : '?').join('\u00D7');
  2327. content = content.length > 16 ? '' : content;
  2328. }
  2329. if (this.context.options.names) {
  2330. content = this.value.name.split('\n').shift(); // custom argument id
  2331. }
  2332. const edge = this.from.edge(to);
  2333. if (!edge.value) {
  2334. edge.value = this;
  2335. if (content) {
  2336. edge.label = content;
  2337. }
  2338. edge.id = `edge-${this.value.name}`;
  2339. if (this._controlDependencies && this._controlDependencies.has(i)) {
  2340. edge.class = 'edge-path-control-dependency';
  2341. }
  2342. }
  2343. this.context.setEdge(edge);
  2344. this._edges.push(edge);
  2345. }
  2346. }
  2347. }
  2348. select() {
  2349. let array = [];
  2350. if (Array.isArray(this._edges)) {
  2351. for (const edge of this._edges) {
  2352. array = array.concat(edge.select());
  2353. }
  2354. }
  2355. return array;
  2356. }
  2357. deselect() {
  2358. if (Array.isArray(this._edges)) {
  2359. for (const edge of this._edges) {
  2360. edge.deselect();
  2361. }
  2362. }
  2363. }
  2364. activate() {
  2365. if (this.value && this.from && Array.isArray(this.to) && !this.value.initializer) {
  2366. const from = this.from.value;
  2367. const to = this.to.map((node) => node.value);
  2368. this.context.view.showConnectionProperties(this.value, from, to);
  2369. } else if (this.value && this.value.initializer) {
  2370. this.context.view.showTensorProperties({ value: [this.value] });
  2371. }
  2372. }
  2373. };
  2374. view.Argument = class extends grapher.Argument {
  2375. constructor(context, value) {
  2376. const name = value.name;
  2377. let content = '';
  2378. let separator = '';
  2379. let tooltip = '';
  2380. if (Array.isArray(value.value) && value.value.length === 1 && value.value[0].initializer) {
  2381. const tensor = value.value[0].initializer;
  2382. const type = value.value[0].type;
  2383. tooltip = type.toString();
  2384. content = view.Formatter.tensor(tensor);
  2385. if (!content.startsWith('\u3008')) {
  2386. separator = ' = ';
  2387. }
  2388. }
  2389. super(name, content);
  2390. this.context = context;
  2391. this.value = value;
  2392. this.separator = separator;
  2393. this.tooltip = tooltip;
  2394. }
  2395. focus() {
  2396. this.context.focus([this.value]);
  2397. }
  2398. blur() {
  2399. this.context.blur([this.value]);
  2400. }
  2401. activate() {
  2402. this.context.view.showTensorProperties(this.value);
  2403. }
  2404. };
  2405. view.Edge = class extends grapher.Edge {
  2406. constructor(from, to) {
  2407. super(from, to);
  2408. this.v = from.name;
  2409. this.w = to.name;
  2410. }
  2411. get minlen() {
  2412. if (this.from.inputs.every((argument) => (!argument.type || argument.type.endsWith('*')) && argument.value.every((value) => value.initializer))) {
  2413. return 2;
  2414. }
  2415. return 1;
  2416. }
  2417. focus() {
  2418. this.value.context.focus([this.value.value]);
  2419. }
  2420. blur() {
  2421. this.value.context.blur([this.value.value]);
  2422. }
  2423. activate() {
  2424. this.value.context.activate(this.value.value);
  2425. }
  2426. };
  2427. view.Sidebar = class {
  2428. constructor(host) {
  2429. this._host = host;
  2430. this._stack = [];
  2431. const pop = () => this._update(this._stack.slice(0, -1));
  2432. this._closeSidebarHandler = () => pop();
  2433. this._closeSidebarKeyDownHandler = (e) => {
  2434. if (e.keyCode === 27) {
  2435. e.stopPropagation();
  2436. e.preventDefault();
  2437. pop();
  2438. }
  2439. };
  2440. const sidebar = this._element('sidebar');
  2441. sidebar.addEventListener('transitionend', (event) => {
  2442. if (event.propertyName === 'opacity' && sidebar.style.opacity === '0') {
  2443. const content = this._element('sidebar-content');
  2444. content.replaceChildren();
  2445. }
  2446. });
  2447. }
  2448. _element(id) {
  2449. return this._host.document.getElementById(id);
  2450. }
  2451. open(content, title) {
  2452. const element = this._render(content);
  2453. const entry = { title, element, content };
  2454. this._update([entry]);
  2455. }
  2456. close() {
  2457. this._update([]);
  2458. }
  2459. push(content, title) {
  2460. const element = this._render(content);
  2461. const entry = { title, content, element };
  2462. this._update(this._stack.concat(entry));
  2463. }
  2464. get identifier() {
  2465. if (this._stack.length > 0) {
  2466. const content = this._stack[this._stack.length - 1].content;
  2467. if (content.identifier) {
  2468. return content.identifier;
  2469. }
  2470. }
  2471. return '';
  2472. }
  2473. _render(content) {
  2474. try {
  2475. content.render();
  2476. } catch (error) {
  2477. content.error(error, false);
  2478. }
  2479. const element = content.element;
  2480. return Array.isArray(element) ? element : [element];
  2481. }
  2482. _update(stack) {
  2483. const sidebar = this._element('sidebar');
  2484. const element = this._element('sidebar-content');
  2485. const container = this._element('target');
  2486. const closeButton = this._element('sidebar-closebutton');
  2487. closeButton.removeEventListener('click', this._closeSidebarHandler);
  2488. this._host.document.removeEventListener('keydown', this._closeSidebarKeyDownHandler);
  2489. if (this._stack.length > 0) {
  2490. const entry = this._stack.pop();
  2491. const content = entry.content;
  2492. if (content && content.deactivate) {
  2493. content.deactivate();
  2494. }
  2495. }
  2496. if (stack) {
  2497. this._stack = stack;
  2498. }
  2499. if (this._stack.length > 0) {
  2500. const entry = this._stack[this._stack.length - 1];
  2501. this._element('sidebar-title').innerHTML = entry.title || '';
  2502. closeButton.addEventListener('click', this._closeSidebarHandler);
  2503. if (typeof entry.content === 'string') {
  2504. element.innerHTML = entry.element;
  2505. } else if (entry.element instanceof Array) {
  2506. element.replaceChildren(...entry.element);
  2507. } else {
  2508. element.replaceChildren(entry.element);
  2509. }
  2510. sidebar.style.width = 'min(calc(100% * 0.6), 42em)';
  2511. sidebar.style.right = 0;
  2512. sidebar.style.opacity = 1;
  2513. this._host.document.addEventListener('keydown', this._closeSidebarKeyDownHandler);
  2514. container.style.width = 'max(40vw, calc(100vw - 42em))';
  2515. const content = entry.content;
  2516. if (content && content.activate) {
  2517. content.activate();
  2518. }
  2519. } else {
  2520. sidebar.style.right = 'calc(0px - min(calc(100% * 0.6), 42em))';
  2521. sidebar.style.opacity = 0;
  2522. const clone = element.cloneNode(true);
  2523. element.parentNode.replaceChild(clone, element);
  2524. container.style.width = '100%';
  2525. container.focus();
  2526. }
  2527. }
  2528. };
  2529. view.Control = class {
  2530. constructor(context) {
  2531. this._view = context;
  2532. this._host = context.host;
  2533. }
  2534. createElement(tagName, className) {
  2535. const element = this._host.document.createElement(tagName);
  2536. if (className) {
  2537. element.setAttribute('class', className);
  2538. }
  2539. return element;
  2540. }
  2541. on(event, callback) {
  2542. this._events = this._events || {};
  2543. this._events[event] = this._events[event] || [];
  2544. this._events[event].push(callback);
  2545. }
  2546. emit(event, data) {
  2547. try {
  2548. if (this._events && this._events[event]) {
  2549. for (const callback of this._events[event]) {
  2550. callback(this, data);
  2551. }
  2552. }
  2553. } catch (error) {
  2554. this.error(error, false);
  2555. }
  2556. }
  2557. error(error, fatal) {
  2558. this._view.exception(error, fatal || false);
  2559. }
  2560. };
  2561. view.Expander = class extends view.Control {
  2562. constructor(context) {
  2563. super(context);
  2564. this.element = this.createElement('div', 'sidebar-item-value');
  2565. this._count = -1;
  2566. }
  2567. render() {
  2568. return [this.element];
  2569. }
  2570. enable() {
  2571. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2572. this._expander.innerText = '+';
  2573. this._expander.addEventListener('click', () => this.toggle());
  2574. this.add(this._expander);
  2575. }
  2576. add(element) {
  2577. this.element.appendChild(element);
  2578. }
  2579. control(element) {
  2580. this.add(element);
  2581. }
  2582. toggle() {
  2583. this._count = this._count === -1 ? this.element.childElementCount : this._count;
  2584. if (this._expander) {
  2585. while (this.element.childElementCount > this._count) {
  2586. this.element.removeChild(this.element.lastChild);
  2587. }
  2588. if (this._expander.innerText === '+') {
  2589. this._expander.innerText = '-';
  2590. this.expand();
  2591. } else {
  2592. this._expander.innerText = '+';
  2593. this.collapse();
  2594. }
  2595. }
  2596. }
  2597. expand() {
  2598. }
  2599. collapse() {
  2600. }
  2601. };
  2602. view.TargetSelector = class extends view.Control {
  2603. constructor(context, element) {
  2604. super(context);
  2605. this._element = element;
  2606. [this._select] = element.getElementsByTagName('select');
  2607. this._select.addEventListener('change', (e) => {
  2608. const target = this._targets[e.target.selectedIndex];
  2609. this.emit('change', target);
  2610. });
  2611. this._targets = [];
  2612. }
  2613. update(model, stack) {
  2614. while (this._select.firstChild) {
  2615. this._select.removeChild(this._select.firstChild);
  2616. }
  2617. this._targets = [];
  2618. const current = stack.length > 0 ? stack[stack.length - 1] : null;
  2619. const section = (title, targets) => {
  2620. if (targets.length > 0) {
  2621. const group = this.createElement('optgroup');
  2622. group.setAttribute('label', title);
  2623. this._select.appendChild(group);
  2624. for (let i = 0; i < targets.length; i++) {
  2625. const target = targets[i];
  2626. const option = this.createElement('option');
  2627. option.innerText = target.name;
  2628. group.appendChild(option);
  2629. if (current && current.target === target.target && current.signature === target.signature) {
  2630. option.setAttribute('selected', 'true');
  2631. this._select.setAttribute('title', target.name);
  2632. }
  2633. this._targets.push(target);
  2634. }
  2635. }
  2636. };
  2637. const modules = [];
  2638. const signatures = [];
  2639. const functions = [];
  2640. if (model && Array.isArray(model.modules)) {
  2641. for (const graph of model.modules) {
  2642. const name = graph.name || '(unnamed)';
  2643. modules.push({ name, target: graph, signature: null });
  2644. if (Array.isArray(graph.functions)) {
  2645. for (const func of graph.functions) {
  2646. functions.push({ name: `${name}.${func.name}`, target: func, signature: null });
  2647. }
  2648. }
  2649. if (Array.isArray(graph.signatures)) {
  2650. for (const signature of graph.signatures) {
  2651. signatures.push({ name: `${name}.${signature.name}`, target: graph, signature });
  2652. }
  2653. }
  2654. }
  2655. }
  2656. if (model && Array.isArray(model.functions)) {
  2657. for (const func of model.functions) {
  2658. functions.push({ name: func.name, target: func, signature: null });
  2659. }
  2660. }
  2661. section('Modules', modules);
  2662. section('Signatures', signatures);
  2663. section('Functions', functions);
  2664. const visible = functions.length > 0 || signatures.length > 0 || modules.length > 1;
  2665. this._element.style.display = visible ? 'inline' : 'none';
  2666. }
  2667. };
  2668. view.ObjectSidebar = class extends view.Control {
  2669. constructor(context) {
  2670. super(context);
  2671. this.element = this.createElement('div', 'sidebar-object');
  2672. }
  2673. addSection(title) {
  2674. const element = this.createElement('div', 'sidebar-section');
  2675. element.innerText = title;
  2676. this.element.appendChild(element);
  2677. }
  2678. addEntry(name, item) {
  2679. const entry = new view.NameValueView(this._view, name, item);
  2680. const element = entry.render();
  2681. this.element.appendChild(element);
  2682. }
  2683. addProperty(name, value, style) {
  2684. const item = new view.TextView(this._view, value, style);
  2685. this.addEntry(name, item);
  2686. return item;
  2687. }
  2688. addArgument(name, argument, source) {
  2689. const value = new view.ArgumentView(this._view, argument, source);
  2690. value.on('focus', (sender, value) => {
  2691. this.emit('focus', value);
  2692. this._focused = this._focused || new Set();
  2693. this._focused.add(value);
  2694. });
  2695. value.on('blur', (sender, value) => {
  2696. this.emit('blur', value);
  2697. this._focused = this._focused || new Set();
  2698. this._focused.delete(value);
  2699. });
  2700. value.on('select', (sender, value) => this.emit('select', value));
  2701. value.on('activate', (sender, value) => this.emit('activate', value));
  2702. value.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2703. this.addEntry(name, value);
  2704. return value;
  2705. }
  2706. error(error, fatal) {
  2707. super.error(error, fatal);
  2708. const element = this.createElement('span');
  2709. const title = document.createElement('b');
  2710. title.textContent = 'ERROR: ';
  2711. element.appendChild(title);
  2712. const message = document.createTextNode(` ${error.message}`);
  2713. element.appendChild(message);
  2714. this.element.appendChild(element);
  2715. }
  2716. };
  2717. view.NodeSidebar = class extends view.ObjectSidebar {
  2718. constructor(context, node) {
  2719. super(context);
  2720. this._node = node;
  2721. }
  2722. get identifier() {
  2723. return 'node';
  2724. }
  2725. render() {
  2726. const node = this._node;
  2727. if (node.type) {
  2728. const type = node.type;
  2729. const item = this.addProperty('type', node.type.identifier || node.type.name);
  2730. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  2731. let icon = '?';
  2732. let tooltip = 'Show Definition';
  2733. if (type.type === 'weights') {
  2734. icon = '\u25CF';
  2735. tooltip = 'Show Weights';
  2736. } else if (Array.isArray(type.nodes)) {
  2737. icon = '\u0192';
  2738. }
  2739. item.action(icon, tooltip, () => {
  2740. this.emit('show-definition', null);
  2741. });
  2742. }
  2743. const module = node.type.module;
  2744. const version = node.type.version;
  2745. const status = node.type.status;
  2746. if (module || version || status) {
  2747. const list = [module, version ? `v${version}` : '', status];
  2748. const value = list.filter((value) => value).join(' ');
  2749. this.addProperty('module', value, 'nowrap');
  2750. }
  2751. }
  2752. if (node.name) {
  2753. this.addProperty('name', node.name, 'nowrap');
  2754. }
  2755. if (node.identifier) {
  2756. this.addProperty('identifier', node.identifier, 'nowrap');
  2757. }
  2758. if (node.description) {
  2759. this.addProperty('description', node.description);
  2760. }
  2761. if (node.device) {
  2762. this.addProperty('device', node.device);
  2763. }
  2764. const attributes = node.attributes;
  2765. if (Array.isArray(attributes) && attributes.length > 0) {
  2766. this.addSection('Attributes');
  2767. attributes.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
  2768. for (const attribute of attributes) {
  2769. this.addArgument(attribute.name, attribute, 'attribute');
  2770. }
  2771. }
  2772. const inputs = node.inputs;
  2773. if (Array.isArray(inputs) && inputs.length > 0) {
  2774. this.addSection('Inputs');
  2775. for (const input of inputs) {
  2776. const name = input.name;
  2777. this.addArgument(name, input);
  2778. }
  2779. }
  2780. const outputs = node.outputs;
  2781. if (Array.isArray(outputs) && outputs.length > 0) {
  2782. this.addSection('Outputs');
  2783. for (const output of outputs) {
  2784. const name = output.name;
  2785. this.addArgument(name, output);
  2786. }
  2787. }
  2788. const metadata = this._view.model.attachment.metadata.node(node);
  2789. if (Array.isArray(metadata) && metadata.length > 0) {
  2790. this.addSection('Metadata');
  2791. for (const argument of metadata) {
  2792. this.addArgument(argument.name, argument, 'attribute');
  2793. }
  2794. }
  2795. const metrics = this._view.model.attachment.metrics.node(node);
  2796. if (Array.isArray(metrics) && metrics.length > 0) {
  2797. this.addSection('Metrics');
  2798. for (const argument of metrics) {
  2799. this.addArgument(argument.name, argument, 'attribute');
  2800. }
  2801. }
  2802. }
  2803. activate() {
  2804. this.emit('select', this._node);
  2805. }
  2806. deactivate() {
  2807. this.emit('select', null);
  2808. if (this._focused) {
  2809. for (const value of this._focused) {
  2810. this.emit('blur', value);
  2811. }
  2812. this._focused.clear();
  2813. }
  2814. }
  2815. };
  2816. view.NameValueView = class extends view.Control {
  2817. constructor(context, name, value) {
  2818. super(context);
  2819. this._name = name;
  2820. this._value = value;
  2821. const nameElement = this.createElement('div', 'sidebar-item-name');
  2822. const input = this.createElement('input');
  2823. input.setAttribute('type', 'text');
  2824. input.setAttribute('value', name);
  2825. input.setAttribute('title', name);
  2826. input.setAttribute('readonly', 'true');
  2827. nameElement.appendChild(input);
  2828. const valueElement = this.createElement('div', 'sidebar-item-value-list');
  2829. for (const element of value.render()) {
  2830. valueElement.appendChild(element);
  2831. }
  2832. this.element = this.createElement('div', 'sidebar-item');
  2833. this.element.appendChild(nameElement);
  2834. this.element.appendChild(valueElement);
  2835. }
  2836. get name() {
  2837. return this._name;
  2838. }
  2839. render() {
  2840. return this.element;
  2841. }
  2842. toggle() {
  2843. this._value.toggle();
  2844. }
  2845. };
  2846. view.TextView = class extends view.Control {
  2847. constructor(context, value, style) {
  2848. super(context);
  2849. this.element = this.createElement('div', 'sidebar-item-value');
  2850. let className = 'sidebar-item-value-line';
  2851. if (value !== null && value !== undefined) {
  2852. const list = Array.isArray(value) ? value : [value];
  2853. for (const item of list) {
  2854. const line = this.createElement('div', className);
  2855. switch (style) {
  2856. case 'code': {
  2857. const element = this.createElement('code');
  2858. element.textContent = item;
  2859. line.appendChild(element);
  2860. break;
  2861. }
  2862. case 'bold': {
  2863. const element = this.createElement('b');
  2864. element.textContent = item;
  2865. line.appendChild(element);
  2866. break;
  2867. }
  2868. case 'nowrap': {
  2869. line.innerText = item;
  2870. line.style.whiteSpace = style;
  2871. break;
  2872. }
  2873. default: {
  2874. line.innerText = item;
  2875. break;
  2876. }
  2877. }
  2878. this.element.appendChild(line);
  2879. className = 'sidebar-item-value-line-border';
  2880. }
  2881. } else {
  2882. const line = this.createElement('div', className);
  2883. line.classList.add('sidebar-item-disable-select');
  2884. line.innerHTML = '&nbsp';
  2885. this.element.appendChild(line);
  2886. }
  2887. }
  2888. action(text, description, callback) {
  2889. const action = this.createElement('div', 'sidebar-item-value-expander');
  2890. action.setAttribute('title', description);
  2891. action.addEventListener('click', () => callback());
  2892. action.innerHTML = text;
  2893. this.element.insertBefore(action, this.element.childNodes[0]);
  2894. }
  2895. render() {
  2896. return [this.element];
  2897. }
  2898. toggle() {
  2899. }
  2900. };
  2901. view.ArgumentView = class extends view.Control {
  2902. constructor(context, argument, source) {
  2903. super(context);
  2904. this._argument = argument;
  2905. this._source = source;
  2906. this._elements = [];
  2907. this._items = [];
  2908. const type = argument.type === 'attribute' ? null : argument.type;
  2909. let value = argument.value;
  2910. if (argument.type === 'attribute') {
  2911. this._source = 'attribute';
  2912. }
  2913. if (argument.type === 'tensor' || argument.type === 'tensor?') {
  2914. if (value === null || (value && value.constructor && value.constructor.name === 'Value')) {
  2915. value = [value];
  2916. } else {
  2917. value = [{ type: value.type, initializer: value }];
  2918. }
  2919. } else if (argument.type === 'tensor[]' || argument.type === 'tensor?[]') {
  2920. value = value.map((value) => {
  2921. if (value === null || (value && value.constructor && value.constructor.name === 'Value')) {
  2922. return value;
  2923. }
  2924. return { type: value.type, initializer: value };
  2925. });
  2926. }
  2927. this._source = typeof type === 'string' && !type.endsWith('*') ? 'attribute' : this._source;
  2928. const primitive = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint';
  2929. if (primitive) {
  2930. const item = new view.PrimitiveView(context, argument);
  2931. this._items.push(item);
  2932. } else if (this._source === 'attribute' && type !== 'tensor' && type !== 'tensor?' && type !== 'tensor[]' && type !== 'tensor?[]') {
  2933. this._source = 'attribute';
  2934. const item = new view.PrimitiveView(context, argument);
  2935. this._items.push(item);
  2936. } else if (Array.isArray(value) && value.length === 0) {
  2937. const item = new view.TextView(this._view, null);
  2938. this._items.push(item);
  2939. } else {
  2940. const values = value;
  2941. for (const value of values) {
  2942. const emit = values.length === 1 && value && value.initializer;
  2943. const target = emit ? argument : value;
  2944. if (value === null) {
  2945. const item = new view.TextView(this._view, null);
  2946. this._items.push(item);
  2947. } else {
  2948. const item = new view.ValueView(context, value, this._source);
  2949. item.on('focus', () => this.emit('focus', target));
  2950. item.on('blur', () => this.emit('blur', target));
  2951. item.on('activate', () => this.emit('activate', target));
  2952. item.on('select', () => this.emit('select', target));
  2953. this._items.push(item);
  2954. }
  2955. }
  2956. }
  2957. for (const item of this._items) {
  2958. this._elements.push(...item.render());
  2959. }
  2960. }
  2961. render() {
  2962. return this._elements;
  2963. }
  2964. toggle() {
  2965. for (const item of this._items) {
  2966. item.toggle();
  2967. }
  2968. }
  2969. };
  2970. view.PrimitiveView = class extends view.Expander {
  2971. constructor(context, argument) {
  2972. super(context);
  2973. try {
  2974. this._argument = argument;
  2975. const type = argument.type === 'attribute' ? null : argument.type;
  2976. const value = argument.value;
  2977. if (type) {
  2978. this.enable();
  2979. }
  2980. switch (type) {
  2981. case 'graph': {
  2982. const line = this.createElement('div', 'sidebar-item-value-line-link');
  2983. line.textContent = value.name || '\u00A0';
  2984. line.addEventListener('click', () => this.emit('activate', value));
  2985. this.add(line);
  2986. break;
  2987. }
  2988. case 'function': {
  2989. const line = this.createElement('div', 'sidebar-item-value-line-link');
  2990. line.textContent = value.type.name;
  2991. line.addEventListener('click', () => this.emit('activate', value));
  2992. this.add(line);
  2993. break;
  2994. }
  2995. case 'object[]': {
  2996. for (const obj of argument.value) {
  2997. const line = this.createElement('div', 'sidebar-item-value-line');
  2998. line.textContent = obj.type ? obj.type.name : '?';
  2999. this.add(line);
  3000. }
  3001. break;
  3002. }
  3003. default: {
  3004. const formatter = new view.Formatter(value, type);
  3005. let content = formatter.toString();
  3006. if (content && content.length > 1000) {
  3007. content = `${content.substring(0, 1000)}\u2026`;
  3008. }
  3009. if (content && typeof content === 'string') {
  3010. content = content.split('<').join('&lt;').split('>').join('&gt;');
  3011. }
  3012. if (content.indexOf('\n') >= 0) {
  3013. content = content.split('\n').join('<br>');
  3014. }
  3015. const line = this.createElement('div', 'sidebar-item-value-line');
  3016. line.innerHTML = content ? content : '&nbsp;';
  3017. this.add(line);
  3018. }
  3019. }
  3020. } catch (error) {
  3021. super.error(error, false);
  3022. this._info('ERROR', error.message);
  3023. }
  3024. }
  3025. expand() {
  3026. try {
  3027. const type = this._argument.type;
  3028. const value = this._argument.value;
  3029. const content = type === 'tensor' && value && value.type ? value.type.toString() : this._argument.type;
  3030. const line = this.createElement('div', 'sidebar-item-value-line-border');
  3031. line.innerHTML = `type: <code><b>${content}</b></code>`;
  3032. this.add(line);
  3033. const description = this._argument.description;
  3034. if (description) {
  3035. const line = this.createElement('div', 'sidebar-item-value-line-border');
  3036. line.innerHTML = description;
  3037. this.add(line);
  3038. }
  3039. } catch (error) {
  3040. super.error(error, false);
  3041. this._info('ERROR', error.message);
  3042. }
  3043. }
  3044. _info(name, value) {
  3045. const line = this.createElement('div');
  3046. line.innerHTML = `<b>${name}:</b> ${value}`;
  3047. this._add(line);
  3048. }
  3049. _add(child) {
  3050. child.className = this._first === false ? 'sidebar-item-value-line-border' : 'sidebar-item-value-line';
  3051. this.add(child);
  3052. this._first = false;
  3053. }
  3054. };
  3055. view.ValueView = class extends view.Expander {
  3056. constructor(context, value, source) {
  3057. super(context);
  3058. this._value = value;
  3059. try {
  3060. if (value && value.constructor && value.constructor.name === 'Value' && source === 'attribute') {
  3061. source = '';
  3062. }
  3063. const type = this._value.type;
  3064. const initializer = this._value.initializer;
  3065. const quantization = this._value.quantization;
  3066. const location = this._value.location !== undefined;
  3067. if (initializer) {
  3068. this.element.classList.add('sidebar-item-value-content');
  3069. }
  3070. if (type || initializer || quantization || location || source === 'attribute') {
  3071. this.enable();
  3072. }
  3073. if (initializer && source !== 'attribute') {
  3074. const element = this.createElement('div', 'sidebar-item-value-button');
  3075. element.classList.add('sidebar-item-value-button-tool');
  3076. element.setAttribute('title', 'Show Tensor');
  3077. element.innerHTML = `<svg class='sidebar-find-content-icon'><use href="#sidebar-icon-weight"></use></svg>`;
  3078. element.addEventListener('pointerenter', () => this.emit('focus', this._value));
  3079. element.addEventListener('pointerleave', () => this.emit('blur', this._value));
  3080. element.style.cursor = 'pointer';
  3081. element.addEventListener('click', () => this.emit('activate', this._value));
  3082. this.control(element);
  3083. }
  3084. const name = this._value.name ? this._value.name.split('\n').shift() : ''; // custom argument id
  3085. this._hasId = name && source !== 'attribute' ? true : false;
  3086. this._hasCategory = initializer && initializer.category && source !== 'attribute' ? true : false;
  3087. if (this._hasId || (!this._hasCategory && !type && source !== 'attribute')) {
  3088. this._hasId = true;
  3089. const element = this.createElement('div', 'sidebar-item-value-line');
  3090. if (typeof name !== 'string') {
  3091. throw new Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  3092. }
  3093. const text = this.createElement('b');
  3094. text.innerText = name || ' ';
  3095. const line = this.createElement('span', 'sidebar-item-value-line-content');
  3096. line.innerText = 'name: ';
  3097. line.appendChild(text);
  3098. element.appendChild(line);
  3099. element.addEventListener('pointerenter', () => this.emit('focus', this._value));
  3100. element.addEventListener('pointerleave', () => this.emit('blur', this._value));
  3101. element.style.cursor = 'pointer';
  3102. element.addEventListener('click', () => this.emit('activate', this._value));
  3103. this._add(element);
  3104. } else if (this._hasCategory) {
  3105. this._bold('category', initializer.category);
  3106. } else if (type) {
  3107. const value = type.toString().split('<').join('&lt;').split('>').join('&gt;');
  3108. this._code('tensor', value);
  3109. }
  3110. } catch (error) {
  3111. super.error(error, false);
  3112. this._info('ERROR', error.message);
  3113. }
  3114. }
  3115. render() {
  3116. return [this.element];
  3117. }
  3118. expand() {
  3119. try {
  3120. const initializer = this._value.initializer;
  3121. if (this._hasId && this._hasCategory) {
  3122. this._bold('category', initializer.category);
  3123. }
  3124. let type = null;
  3125. let denotation = null;
  3126. if (this._value.type) {
  3127. type = this._value.type.toString();
  3128. denotation = this._value.type.denotation || null;
  3129. }
  3130. if (type && (this._hasId || this._hasCategory)) {
  3131. this._code('tensor', type.split('<').join('&lt;').split('>').join('&gt;'));
  3132. }
  3133. if (denotation) {
  3134. this._code('denotation', denotation);
  3135. }
  3136. const description = this._value.description;
  3137. if (description) {
  3138. const line = this.createElement('div', 'sidebar-item-value-line-border');
  3139. line.innerHTML = description;
  3140. this.add(line);
  3141. }
  3142. const identifier = this._value.identifier;
  3143. if (identifier !== undefined) {
  3144. this._bold('identifier', identifier);
  3145. }
  3146. const layout = this._value.type ? this._value.type.layout : null;
  3147. if (layout) {
  3148. this._bold('layout', layout.replace('.', ' '));
  3149. }
  3150. const quantization = this._value.quantization;
  3151. if (quantization) {
  3152. if (typeof quantization.type !== 'string') {
  3153. throw new view.Error('Unsupported quantization value.');
  3154. }
  3155. const value = new view.Quantization(quantization).toString();
  3156. if (quantization.type && (quantization.type !== 'linear' || (value && value !== 'q'))) {
  3157. const line = this.createElement('div', 'sidebar-item-value-line-border');
  3158. const content = [
  3159. `<span class='sidebar-item-value-line-content'>quantization: <b>${quantization.type}</b></span>`
  3160. ];
  3161. if (value) {
  3162. content.push(`<pre style='margin: 4px 0 2px 0'>${value}</pre>`);
  3163. }
  3164. line.innerHTML = content.join('');
  3165. this._add(line);
  3166. }
  3167. }
  3168. if (initializer) {
  3169. if (initializer.location) {
  3170. this._bold('location', initializer.location);
  3171. }
  3172. const stride = initializer.stride;
  3173. if (Array.isArray(stride) && stride.length > 0) {
  3174. this._code('stride', stride.join(','));
  3175. }
  3176. const tensor = new view.TensorView(this._view, initializer);
  3177. const content = tensor.content;
  3178. const line = this.createElement('div', 'sidebar-item-value-line-border');
  3179. line.appendChild(content);
  3180. this._add(line);
  3181. }
  3182. } catch (error) {
  3183. super.error(error, false);
  3184. this._info('ERROR', error.message);
  3185. }
  3186. }
  3187. _bold(name, value) {
  3188. const line = this.createElement('div');
  3189. line.innerHTML = `${name}: <b>${value}</b>`;
  3190. this._add(line);
  3191. }
  3192. _code(name, value) {
  3193. const line = this.createElement('div');
  3194. line.innerHTML = `${name}: <code><b>${value}</b></code>`;
  3195. this._add(line);
  3196. }
  3197. _info(name, value) {
  3198. const line = this.createElement('div');
  3199. line.innerHTML = `<b>${name}:</b> ${value}`;
  3200. this._add(line);
  3201. }
  3202. _add(child) {
  3203. child.className = this._first === false ? 'sidebar-item-value-line-border' : 'sidebar-item-value-line';
  3204. this.add(child);
  3205. this._first = false;
  3206. }
  3207. };
  3208. view.TensorView = class extends view.Expander {
  3209. constructor(context, value, tensor) {
  3210. super(context);
  3211. this._value = value;
  3212. this._tensor = tensor || new base.Tensor(value);
  3213. }
  3214. render() {
  3215. if (!this._button) {
  3216. this.enable();
  3217. this._button = this.createElement('div', 'sidebar-item-value-button');
  3218. this._button.setAttribute('style', 'float: left;');
  3219. this._button.innerHTML = `<svg class='sidebar-find-content-icon'><use href="#sidebar-icon-weight"></use></svg>`;
  3220. this._button.addEventListener('click', () => this.toggle());
  3221. this.control(this._button);
  3222. const line = this.createElement('div', 'sidebar-item-value-line');
  3223. line.classList.add('sidebar-item-disable-select');
  3224. line.innerHTML = '&nbsp';
  3225. this.element.appendChild(line);
  3226. }
  3227. return super.render();
  3228. }
  3229. expand() {
  3230. try {
  3231. const content = this.content;
  3232. const container = this.createElement('div', 'sidebar-item-value-line-border');
  3233. container.appendChild(content);
  3234. this.element.appendChild(container);
  3235. } catch (error) {
  3236. this.error(error, false);
  3237. }
  3238. }
  3239. get content() {
  3240. const content = this.createElement('pre');
  3241. const value = this._value;
  3242. const tensor = this._tensor;
  3243. if (tensor.encoding !== '<' && tensor.encoding !== '>' && tensor.encoding !== '|') {
  3244. content.innerHTML = `Tensor encoding '${tensor.layout}' is not implemented.`;
  3245. } else if (tensor.layout && (tensor.layout !== 'sparse' && tensor.layout !== 'sparse.coo')) {
  3246. content.innerHTML = `Tensor layout '${tensor.layout}' is not implemented.`;
  3247. } else if (tensor.type && tensor.type.dataType === '?') {
  3248. content.innerHTML = 'Tensor data type is not defined.';
  3249. } else if (tensor.type && !tensor.type.shape) {
  3250. content.innerHTML = 'Tensor shape is not defined.';
  3251. } else {
  3252. content.innerHTML = '&#x23F3';
  3253. const promise = value.peek && !value.peek() ? value.read() : Promise.resolve();
  3254. promise.then(() => {
  3255. if (tensor.empty) {
  3256. content.innerHTML = 'Tensor data is empty.';
  3257. } else {
  3258. content.innerHTML = tensor.toString();
  3259. if (this._host.save && value.type.shape && value.type.shape.dimensions && value.type.shape.dimensions.length > 0) {
  3260. this._saveButton = this.createElement('div', 'sidebar-item-value-button');
  3261. this._saveButton.classList.add('sidebar-item-value-button-context');
  3262. this._saveButton.setAttribute('style', 'float: right;');
  3263. this._saveButton.innerHTML = '&#x1F4BE;';
  3264. this._saveButton.addEventListener('click', async () => {
  3265. await this.export();
  3266. });
  3267. content.insertBefore(this._saveButton, content.firstChild);
  3268. }
  3269. }
  3270. }).catch((error) => {
  3271. content.innerHTML = error.message;
  3272. });
  3273. }
  3274. return content;
  3275. }
  3276. error(error, fatal) {
  3277. super.error(error, fatal);
  3278. const element = this.createElement('div', 'sidebar-item-value-line');
  3279. const title = document.createElement('b');
  3280. title.textContent = 'ERROR: ';
  3281. element.appendChild(title);
  3282. const message = document.createTextNode(error.message);
  3283. element.appendChild(message);
  3284. this.element.appendChild(element);
  3285. }
  3286. async export() {
  3287. const tensor = this._tensor;
  3288. const defaultPath = tensor.name ? tensor.name.split('/').join('_').split(':').join('_').split('.').join('_') : 'tensor';
  3289. const file = await this._host.save('NumPy Array', 'npy', defaultPath);
  3290. if (file) {
  3291. try {
  3292. let data_type = '?';
  3293. switch (tensor.type.dataType) {
  3294. case 'boolean': data_type = 'bool'; break;
  3295. case 'bfloat16': data_type = 'float32'; break;
  3296. case 'float8e5m2': data_type = 'float16'; break;
  3297. case 'float8e5m2fnuz': data_type = 'float16'; break;
  3298. case 'float8e4m3fn': data_type = 'float16'; break;
  3299. case 'float8e4m3fnuz': data_type = 'float16'; break;
  3300. case 'int4': data_type = 'int8'; break;
  3301. default: data_type = tensor.type.dataType; break;
  3302. }
  3303. const python = await import('./python.js');
  3304. const execution = new python.Execution();
  3305. const io = execution.__import__('io');
  3306. const numpy = execution.register('numpy');
  3307. const bytes = new io.BytesIO();
  3308. const dtype = new numpy.dtype(data_type);
  3309. const array = numpy.asarray(tensor.value, dtype);
  3310. numpy.save(bytes, array);
  3311. bytes.seek(0);
  3312. const blob = new Blob([bytes.read()], { type: 'application/octet-stream' });
  3313. await this._host.export(file, blob);
  3314. } catch (error) {
  3315. this.error(error, 'Error saving NumPy tensor.', null);
  3316. }
  3317. }
  3318. }
  3319. };
  3320. view.NodeView = class extends view.Expander {
  3321. constructor(context, node) {
  3322. super(context);
  3323. this._node = node;
  3324. const name = node.name;
  3325. const type = node.type ? node.type.name : '';
  3326. if (name && type) {
  3327. this.enable();
  3328. }
  3329. if (type) {
  3330. const type = node.type.name;
  3331. const element = this.createElement('div', 'sidebar-item-value-line');
  3332. element.innerHTML = `<span class='sidebar-item-value-line-content'>node: <b>${type || ' '}</b></span>`;
  3333. element.addEventListener('pointerenter', () => this.emit('focus', this._node));
  3334. element.addEventListener('pointerleave', () => this.emit('blur', this._node));
  3335. element.addEventListener('click', () => this.emit('activate', this._node));
  3336. element.style.cursor = 'pointer';
  3337. this.element.appendChild(element);
  3338. } else {
  3339. const element = this.createElement('div', 'sidebar-item-value-line');
  3340. element.innerHTML = `<span class='sidebar-item-value-line-content'>name: <b>${name || ' '}</b></span>`;
  3341. element.addEventListener('pointerenter', () => this.emit('focus', this._node));
  3342. element.addEventListener('pointerleave', () => this.emit('blur', this._node));
  3343. element.addEventListener('click', () => this.emit('activate', this._node));
  3344. element.style.cursor = 'pointer';
  3345. this.element.appendChild(element);
  3346. }
  3347. }
  3348. expand() {
  3349. const name = this._node.name;
  3350. const element = this.createElement('div', 'sidebar-item-value-line-border');
  3351. element.innerHTML = `<span class='sidebar-item-value-line-content'>name: <b>${name}</b></span>`;
  3352. element.addEventListener('pointerenter', () => this.emit('focus', this._node));
  3353. element.addEventListener('pointerleave', () => this.emit('blur', this._node));
  3354. element.addEventListener('click', () => this.emit('activate', this._node));
  3355. element.style.cursor = 'pointer';
  3356. this.element.appendChild(element);
  3357. }
  3358. };
  3359. view.NodeListView = class extends view.Control {
  3360. constructor(context, list) {
  3361. super(context);
  3362. this._elements = [];
  3363. for (const node of list) {
  3364. const item = new view.NodeView(this._view, node);
  3365. item.on('focus', (sender, value) => this.emit('focus', value));
  3366. item.on('blur', (sender, value) => this.emit('blur', value));
  3367. item.on('activate', (sender, value) => this.emit('activate', value));
  3368. item.on('deactivate', (sender, value) => this.emit('deactivate', value));
  3369. item.on('select', (sender, value) => this.emit('select', value));
  3370. item.toggle();
  3371. for (const element of item.render()) {
  3372. this._elements.push(element);
  3373. }
  3374. }
  3375. }
  3376. render() {
  3377. return this._elements;
  3378. }
  3379. };
  3380. view.ConnectionSidebar = class extends view.ObjectSidebar {
  3381. constructor(context, value, from, to) {
  3382. super(context);
  3383. this._value = value;
  3384. this._from = from;
  3385. this._to = to;
  3386. }
  3387. get identifier() {
  3388. return 'connection';
  3389. }
  3390. render() {
  3391. const value = this._value;
  3392. const from = this._from;
  3393. const to = this._to;
  3394. const [name] = value.name.split('\n');
  3395. this.addProperty('name', name);
  3396. if (value.type) {
  3397. const item = new view.ValueView(this._view, value);
  3398. this.addEntry('type', item);
  3399. item.toggle();
  3400. }
  3401. if (from) {
  3402. this.addSection('Inputs');
  3403. this.addNodeList('from', [from]);
  3404. }
  3405. if (Array.isArray(to) && to.length > 0) {
  3406. this.addSection('Outputs');
  3407. this.addNodeList('to', to);
  3408. }
  3409. const metadata = this._view.model.attachment.metadata.value(value);
  3410. if (Array.isArray(metadata) && metadata.length > 0) {
  3411. this.addSection('Metadata');
  3412. for (const argument of metadata) {
  3413. this.addArgument(argument.name, argument, 'attribute');
  3414. }
  3415. }
  3416. const metrics = this._view.model.attachment.metrics.value(value);
  3417. if (Array.isArray(metrics) && metrics.length > 0) {
  3418. this.addSection('Metrics');
  3419. for (const argument of metrics) {
  3420. this.addArgument(argument.name, argument, 'attribute');
  3421. }
  3422. }
  3423. }
  3424. addNodeList(name, list) {
  3425. const entry = new view.NodeListView(this._view, list);
  3426. entry.on('focus', (sender, value) => {
  3427. this.emit('focus', value);
  3428. this._focused = this._focused || new Set();
  3429. this._focused.add(value);
  3430. });
  3431. entry.on('blur', (sender, value) => {
  3432. this.emit('blur', value);
  3433. this._focused = this._focused || new Set();
  3434. this._focused.delete(value);
  3435. });
  3436. entry.on('select', (sender, value) => this.emit('select', value));
  3437. entry.on('activate', (sender, value) => this.emit('activate', value));
  3438. this.addEntry(name, entry);
  3439. }
  3440. activate() {
  3441. this.emit('select', this._value);
  3442. }
  3443. deactivate() {
  3444. this.emit('select', null);
  3445. if (this._focused) {
  3446. for (const value of this._focused) {
  3447. this.emit('blur', value);
  3448. }
  3449. this._focused.clear();
  3450. }
  3451. }
  3452. };
  3453. view.TensorSidebar = class extends view.ObjectSidebar {
  3454. constructor(context, value) {
  3455. super(context);
  3456. this._value = value;
  3457. }
  3458. get identifier() {
  3459. return 'tensor';
  3460. }
  3461. render() {
  3462. const [value] = this._value.value;
  3463. const tensor = value.initializer;
  3464. const name = tensor && tensor.name ? tensor.name : value.name.split('\n')[0];
  3465. if (name) {
  3466. this.addProperty('name', name);
  3467. }
  3468. if (tensor) {
  3469. const category = tensor.category;
  3470. if (category) {
  3471. this.addProperty('category', category);
  3472. }
  3473. const description = tensor.description;
  3474. if (description) {
  3475. this.addProperty('description', description);
  3476. }
  3477. const type = tensor.type;
  3478. if (type) {
  3479. const dataType = type.dataType;
  3480. this.addProperty('type', `${dataType}`, 'code');
  3481. const shape = type.shape && Array.isArray(type.shape.dimensions) ? type.shape.dimensions.toString(', ') : '?';
  3482. if (shape) {
  3483. this.addProperty('shape', shape, 'code');
  3484. }
  3485. const denotation = type.denotation;
  3486. if (denotation) {
  3487. this.addProperty('denotation', denotation, 'code');
  3488. }
  3489. const layout = type.layout;
  3490. if (layout) {
  3491. this.addProperty('layout', layout.replace('.', ' '));
  3492. }
  3493. }
  3494. const location = tensor.location;
  3495. if (location) {
  3496. this.addProperty('location', tensor.location);
  3497. }
  3498. const stride = tensor.stride;
  3499. if (Array.isArray(stride) && stride.length > 0) {
  3500. this.addProperty('stride', stride.join(','), 'code');
  3501. }
  3502. const value = new view.TensorView(this._view, tensor, this._tensor);
  3503. this.addEntry('value', value);
  3504. const metadata = this._view.model.attachment.metadata.tensor(tensor);
  3505. if (Array.isArray(metadata) && metadata.length > 0) {
  3506. this.addSection('Metadata');
  3507. for (const argument of metadata) {
  3508. this.addArgument(argument.name, argument, 'attribute');
  3509. }
  3510. }
  3511. }
  3512. // Metrics
  3513. if (value.initializer) {
  3514. const tensor = value.initializer;
  3515. const promise = tensor.peek && !tensor.peek() ? tensor.read() : Promise.resolve();
  3516. promise.then(() => {
  3517. this._tensor = new base.Tensor(tensor);
  3518. if (!this._tensor.empty) {
  3519. if (!this._metrics) {
  3520. const tensor = new metrics.Tensor(this._tensor);
  3521. this._metrics = this._view.model.attachment.metrics.tensor(tensor);
  3522. }
  3523. if (this._metrics.length > 0) {
  3524. this.addSection('Metrics');
  3525. for (const metric of this._metrics) {
  3526. const value = metric.type === 'percentage' ? `${(metric.value * 100).toFixed(1)}%` : metric.value;
  3527. const argument = new metadata.Argument(metric.name, value, metric.type);
  3528. this.addArgument(metric.name, argument, 'attribute');
  3529. }
  3530. }
  3531. }
  3532. });
  3533. }
  3534. }
  3535. activate() {
  3536. this.emit('select', this._value);
  3537. }
  3538. deactivate() {
  3539. this.emit('select', null);
  3540. }
  3541. };
  3542. view.ModelSidebar = class extends view.ObjectSidebar {
  3543. constructor(context, model) {
  3544. super(context);
  3545. this._model = model;
  3546. }
  3547. get identifier() {
  3548. return 'model';
  3549. }
  3550. render() {
  3551. const model = this._model;
  3552. if (model.format) {
  3553. this.addProperty('format', model.format);
  3554. }
  3555. if (model.producer) {
  3556. this.addProperty('producer', model.producer);
  3557. }
  3558. if (model.name) {
  3559. this.addProperty('name', model.name);
  3560. }
  3561. if (model.version) {
  3562. this.addProperty('version', model.version);
  3563. }
  3564. if (model.description) {
  3565. this.addProperty('description', model.description);
  3566. }
  3567. if (model.domain) {
  3568. this.addProperty('domain', model.domain);
  3569. }
  3570. if (model.imports) {
  3571. this.addProperty('imports', model.imports);
  3572. }
  3573. if (model.runtime) {
  3574. this.addProperty('runtime', model.runtime);
  3575. }
  3576. if (model.source) {
  3577. this.addProperty('source', model.source);
  3578. }
  3579. const metadata = this._view.model.attachment.metadata.model(model);
  3580. if (Array.isArray(metadata) && metadata.length > 0) {
  3581. this.addSection('Metadata');
  3582. for (const argument of metadata) {
  3583. this.addArgument(argument.name, argument, 'attribute');
  3584. }
  3585. }
  3586. const metrics = this.metrics;
  3587. if (Array.isArray(metrics) && metrics.length > 0) {
  3588. this.addSection('Metrics');
  3589. for (const argument of metrics) {
  3590. this.addArgument(argument.name, argument, 'attribute');
  3591. }
  3592. }
  3593. }
  3594. get metrics() {
  3595. const model = new metrics.Model(this._model);
  3596. return this._view.model.attachment.metrics.model(model);
  3597. }
  3598. };
  3599. view.TargetSidebar = class extends view.ObjectSidebar {
  3600. constructor(context, target, signature) {
  3601. super(context);
  3602. this._target = target;
  3603. this._signature = signature;
  3604. }
  3605. render() {
  3606. const target = this._target;
  3607. const signature = this._signature;
  3608. if (target.name) {
  3609. const item = this.addProperty('name', target.name);
  3610. if (target.type === 'function') {
  3611. item.action('\u0192', 'Show Function Documentation', () => {
  3612. this.emit('show-definition', null);
  3613. });
  3614. }
  3615. }
  3616. if (signature && signature.name) {
  3617. this.addProperty('signature', signature.name);
  3618. }
  3619. if (target.version) {
  3620. this.addProperty('version', target.version);
  3621. }
  3622. if (target.description) {
  3623. this.addProperty('description', target.description);
  3624. }
  3625. const attributes = signature ? signature.attributes : target.attributes;
  3626. const inputs = signature ? signature.inputs : target.inputs;
  3627. const outputs = signature ? signature.outputs : target.outputs;
  3628. if (Array.isArray(attributes) && attributes.length > 0) {
  3629. this.addSection('Attributes');
  3630. for (const attribute of attributes) {
  3631. this.addProperty(attribute.name, attribute.value);
  3632. }
  3633. }
  3634. if (Array.isArray(inputs) && inputs.length > 0) {
  3635. this.addSection('Inputs');
  3636. for (const input of inputs) {
  3637. this.addArgument(input.name, input);
  3638. }
  3639. }
  3640. if (Array.isArray(outputs) && outputs.length > 0) {
  3641. this.addSection('Outputs');
  3642. for (const output of outputs) {
  3643. this.addArgument(output.name, output);
  3644. }
  3645. }
  3646. const metadata = this._view.model.attachment.metadata.graph(target);
  3647. if (Array.isArray(metadata) && metadata.length > 0) {
  3648. this.addSection('Metadata');
  3649. for (const argument of metadata) {
  3650. this.addArgument(argument.name, argument, 'attribute');
  3651. }
  3652. }
  3653. const metrics = this.metrics;
  3654. if (Array.isArray(metrics) && metrics.length > 0) {
  3655. this.addSection('Metrics');
  3656. for (const argument of metrics) {
  3657. this.addArgument(argument.name, argument, 'attribute');
  3658. }
  3659. }
  3660. }
  3661. get metrics() {
  3662. const target = new metrics.Target(this._target);
  3663. return this._view.model.attachment.metrics.graph(target);
  3664. }
  3665. get identifier() {
  3666. return 'target';
  3667. }
  3668. addArgument(name, argument, source) {
  3669. const value = super.addArgument(name, argument, source);
  3670. value.toggle();
  3671. return value;
  3672. }
  3673. };
  3674. view.DocumentationSidebar = class extends view.Control {
  3675. constructor(context, type) {
  3676. super(context);
  3677. this._type = type;
  3678. }
  3679. get identifier() {
  3680. return 'documentation';
  3681. }
  3682. render() {
  3683. if (!this.element) {
  3684. this.element = this.createElement('div', 'sidebar-documentation');
  3685. const type = view.Documentation.open(this._type);
  3686. this._append(this.element, 'h1', type.name);
  3687. if (type.summary) {
  3688. this._append(this.element, 'p', type.summary);
  3689. }
  3690. if (type.description) {
  3691. this._append(this.element, 'p', type.description);
  3692. }
  3693. if (Array.isArray(type.attributes) && type.attributes.length > 0) {
  3694. this._append(this.element, 'h2', 'Attributes');
  3695. const attributes = this._append(this.element, 'dl');
  3696. for (const attribute of type.attributes) {
  3697. this._append(attributes, 'dt', attribute.name + (attribute.type ? `: <tt>${attribute.type}</tt>` : ''));
  3698. this._append(attributes, 'dd', attribute.description);
  3699. }
  3700. this.element.appendChild(attributes);
  3701. }
  3702. if (Array.isArray(type.inputs) && type.inputs.length > 0) {
  3703. this._append(this.element, 'h2', `Inputs${type.inputs_range ? ` (${type.inputs_range})` : ''}`);
  3704. const inputs = this._append(this.element, 'dl');
  3705. for (const input of type.inputs) {
  3706. this._append(inputs, 'dt', input.name + (input.type ? `: <tt>${input.type}</tt>` : '') + (input.option ? ` (${input.option})` : ''));
  3707. this._append(inputs, 'dd', input.description);
  3708. }
  3709. }
  3710. if (Array.isArray(type.outputs) && type.outputs.length > 0) {
  3711. this._append(this.element, 'h2', `Outputs${type.outputs_range ? ` (${type.outputs_range})` : ''}`);
  3712. const outputs = this._append(this.element, 'dl');
  3713. for (const output of type.outputs) {
  3714. this._append(outputs, 'dt', output.name + (output.type ? `: <tt>${output.type}</tt>` : '') + (output.option ? ` (${output.option})` : ''));
  3715. this._append(outputs, 'dd', output.description);
  3716. }
  3717. }
  3718. if (Array.isArray(type.type_constraints) && type.type_constraints.length > 0) {
  3719. this._append(this.element, 'h2', 'Type Constraints');
  3720. const type_constraints = this._append(this.element, 'dl');
  3721. for (const type_constraint of type.type_constraints) {
  3722. this._append(type_constraints, 'dt', `${type_constraint.type_param_str}: ${type_constraint.allowed_type_strs.map((item) => `<tt>${item}</tt>`).join(', ')}`);
  3723. this._append(type_constraints, 'dd', type_constraint.description);
  3724. }
  3725. }
  3726. if (Array.isArray(type.examples) && type.examples.length > 0) {
  3727. this._append(this.element, 'h2', 'Examples');
  3728. for (const example of type.examples) {
  3729. this._append(this.element, 'h3', example.summary);
  3730. this._append(this.element, 'pre', example.code);
  3731. }
  3732. }
  3733. if (Array.isArray(type.references) && type.references.length > 0) {
  3734. this._append(this.element, 'h2', 'References');
  3735. const references = this._append(this.element, 'ul');
  3736. for (const reference of type.references) {
  3737. this._append(references, 'li', reference.description);
  3738. }
  3739. }
  3740. if (this._host.type === 'Electron') {
  3741. this.element.addEventListener('click', (e) => {
  3742. if (e.target && e.target.href) {
  3743. const url = e.target.href;
  3744. if (url.startsWith('http://') || url.startsWith('https://')) {
  3745. e.preventDefault();
  3746. this.emit('navigate', { link: url });
  3747. }
  3748. }
  3749. });
  3750. }
  3751. }
  3752. }
  3753. _append(parent, type, content) {
  3754. const element = this.createElement(type);
  3755. if (content) {
  3756. element.innerHTML = content;
  3757. }
  3758. parent.appendChild(element);
  3759. return element;
  3760. }
  3761. error(error, fatal) {
  3762. super.error(error, fatal);
  3763. const element = this.createElement('span');
  3764. const title = document.createElement('b');
  3765. title.textContent = 'ERROR: ';
  3766. element.appendChild(title);
  3767. const message = document.createTextNode(error.message);
  3768. element.appendChild(message);
  3769. this.element.appendChild(element);
  3770. }
  3771. };
  3772. view.FindSidebar = class extends view.Control {
  3773. constructor(context, state, graph, signature) {
  3774. super(context);
  3775. this._target = graph;
  3776. this._signature = signature;
  3777. this._state = state || {
  3778. query: '',
  3779. node: true,
  3780. connection: true,
  3781. weight: true
  3782. };
  3783. this._toggles = {
  3784. node: { hide: 'Hide Nodes', show: 'Show Nodes' },
  3785. connection: { hide: 'Hide Connections', show: 'Show Connections' },
  3786. weight: { hide: 'Hide Weights', show: 'Show Weights' }
  3787. };
  3788. }
  3789. get identifier() {
  3790. return 'find';
  3791. }
  3792. on(event, callback) {
  3793. this._events = this._events || {};
  3794. this._events[event] = this._events[event] || [];
  3795. this._events[event].push(callback);
  3796. }
  3797. emit(event, data) {
  3798. try {
  3799. if (this._events && this._events[event]) {
  3800. for (const callback of this._events[event]) {
  3801. callback(this, data);
  3802. }
  3803. }
  3804. } catch (error) {
  3805. this.error(error, false);
  3806. }
  3807. }
  3808. _reset() {
  3809. for (const element of this._focused) {
  3810. this._blur(element);
  3811. }
  3812. this._focused.clear();
  3813. this._table.clear();
  3814. this._content.replaceChildren();
  3815. this._edges.clear();
  3816. for (const value of Object.values(this._toggles)) {
  3817. delete value.template;
  3818. }
  3819. const unquote = this._state.query.match(new RegExp(/^'(.*)'|"(.*)"$/));
  3820. if (unquote) {
  3821. this._exact = true;
  3822. const term = unquote[1] || unquote[2];
  3823. this._terms = [term];
  3824. } else {
  3825. this._exact = false;
  3826. this._terms = this._state.query.trim().toLowerCase().split(' ').map((term) => term.trim()).filter((term) => term.length > 0);
  3827. }
  3828. }
  3829. _term(value) {
  3830. if (this._exact) {
  3831. return value === this._terms[0];
  3832. }
  3833. value = value.toLowerCase();
  3834. return this._terms.every((term) => value.indexOf(term) !== -1);
  3835. }
  3836. _value(value) {
  3837. if (this._terms.length === 0) {
  3838. return true;
  3839. }
  3840. if (value.name && this._term(value.name.split('\n').shift())) {
  3841. return true;
  3842. }
  3843. if (value.identifier && this._term(value.identifier)) {
  3844. return true;
  3845. }
  3846. if (value.type && !this._exact) {
  3847. for (const term of this._terms) {
  3848. if (value.type.dataType && term === value.type.dataType.toLowerCase()) {
  3849. return true;
  3850. }
  3851. if (value.type.shape) {
  3852. if (term === value.type.shape.toString().toLowerCase()) {
  3853. return true;
  3854. }
  3855. if (value.type.shape && Array.isArray(value.type.shape.dimensions)) {
  3856. const dimensions = value.type.shape.dimensions.map((dimension) => dimension ? dimension.toString().toLowerCase() : '');
  3857. if (term === dimensions.join(',')) {
  3858. return true;
  3859. }
  3860. if (dimensions.some((dimension) => term === dimension)) {
  3861. return true;
  3862. }
  3863. }
  3864. }
  3865. }
  3866. }
  3867. return false;
  3868. }
  3869. _edge(value) {
  3870. if (value.name && !this._edges.has(value.name) && this._value(value)) {
  3871. const content = `${value.name.split('\n').shift()}`;
  3872. this._add(value, content, 'connection'); // split custom argument id
  3873. this._edges.add(value.name);
  3874. }
  3875. }
  3876. _node(node) {
  3877. if (this._state.connection) {
  3878. const inputs = node.inputs;
  3879. if (Array.isArray(inputs)) {
  3880. for (const input of node.inputs) {
  3881. if (!input.type || input.type.endsWith('*')) {
  3882. for (const value of input.value) {
  3883. if (value !== null && !value.initializer) {
  3884. this._edge(value);
  3885. }
  3886. }
  3887. }
  3888. }
  3889. }
  3890. }
  3891. if (this._state.node) {
  3892. const name = node.name;
  3893. const type = node.type.name;
  3894. const identifier = node.identifier;
  3895. if ((name && this._term(name)) || (type && this._term(type)) || (identifier && this._term(identifier))) {
  3896. const content = `${name || `[${type}]`}`;
  3897. this._add(node, content, 'node');
  3898. }
  3899. }
  3900. if (this._state.weight) {
  3901. const inputs = node.inputs;
  3902. if (Array.isArray(inputs)) {
  3903. for (const argument of node.inputs) {
  3904. if (!argument.type || argument.type.endsWith('*')) {
  3905. for (const value of argument.value) {
  3906. if (value !== null && value.initializer && this._value(value)) {
  3907. let content = null;
  3908. if (value.name) {
  3909. content = `${value.name.split('\n').shift()}`; // split custom argument id
  3910. } else if (Array.isArray(argument.value) && argument.value.length === 1 && argument.name.indexOf('.') !== -1) {
  3911. content = argument.name;
  3912. } else if (value.type && value.type.shape && Array.isArray(value.type.shape.dimensions) && value.type.shape.dimensions.length > 0) {
  3913. content = `${value.type.shape.dimensions.map((d) => (d !== null && d !== undefined) ? d : '?').join('\u00D7')}`;
  3914. }
  3915. if (content) {
  3916. const target = argument.value.length === 1 ? argument : node;
  3917. this._add(target, content, 'weight');
  3918. }
  3919. }
  3920. }
  3921. } else if (argument.type === 'object') {
  3922. this._node(argument.value);
  3923. } else if (argument.type === 'object[]') {
  3924. for (const value of argument.value) {
  3925. this._node(value);
  3926. }
  3927. }
  3928. }
  3929. }
  3930. }
  3931. }
  3932. _add(value, content, type) {
  3933. if (!this._toggles[type].template) {
  3934. const element = this.createElement('li');
  3935. element.innerHTML = `<svg class='sidebar-find-content-icon'><use href="#sidebar-icon-${type}"></use></svg>`;
  3936. this._toggles[type].template = element;
  3937. }
  3938. const element = this._toggles[type].template.cloneNode(true);
  3939. const text = this._host.document.createTextNode(content);
  3940. element.appendChild(text);
  3941. this._table.set(element, value);
  3942. this._content.appendChild(element);
  3943. }
  3944. _focus(element) {
  3945. if (this._table.has(element)) {
  3946. this.emit('focus', this._table.get(element));
  3947. this._focused.add(element);
  3948. }
  3949. }
  3950. _blur(element) {
  3951. if (this._table.has(element)) {
  3952. this.emit('blur', this._table.get(element));
  3953. this._focused.delete(element);
  3954. }
  3955. }
  3956. _update() {
  3957. try {
  3958. this._reset();
  3959. const inputs = this._signature ? this._signature.inputs : this._target.inputs;
  3960. if (this._state.connection) {
  3961. for (const input of inputs) {
  3962. for (const value of input.value) {
  3963. this._edge(value);
  3964. }
  3965. }
  3966. }
  3967. for (const node of this._target.nodes) {
  3968. this._node(node);
  3969. }
  3970. if (this._state.connection) {
  3971. const outputs = this._signature ? this._signature.outputs : this._target.inputs;
  3972. for (const output of outputs) {
  3973. if (!output.type || output.type.endsWith('*')) {
  3974. for (const value of output.value) {
  3975. this._edge(value);
  3976. }
  3977. }
  3978. }
  3979. }
  3980. } catch (error) {
  3981. this.error(error, false);
  3982. }
  3983. }
  3984. render() {
  3985. this._table = new Map();
  3986. this._focused = new Set();
  3987. this._edges = new Set();
  3988. this._search = this.createElement('div', 'sidebar-find-search');
  3989. this._query = this.createElement('input', 'sidebar-find-query');
  3990. this._search.appendChild(this._query);
  3991. this._content = this.createElement('ol', 'sidebar-find-content');
  3992. this._elements = [this._query, this._content];
  3993. this._query.setAttribute('id', 'search');
  3994. this._query.setAttribute('type', 'text');
  3995. this._query.setAttribute('spellcheck', 'false');
  3996. this._query.setAttribute('placeholder', 'Search');
  3997. this._query.addEventListener('input', (e) => {
  3998. this._state.query = e.target.value;
  3999. this.emit('state-changed', this._state);
  4000. this._update();
  4001. });
  4002. this._query.addEventListener('keydown', (e) => {
  4003. if (e.keyCode === 0x08 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4004. e.stopPropagation();
  4005. }
  4006. });
  4007. for (const [name, toggle] of Object.entries(this._toggles)) {
  4008. toggle.element = this.createElement('label', 'sidebar-find-toggle');
  4009. toggle.element.innerHTML = `<svg class='sidebar-find-toggle-icon'><use href="#sidebar-icon-${name}"></use></svg>`;
  4010. toggle.element.setAttribute('title', this._state[name] ? toggle.hide : toggle.show);
  4011. toggle.checkbox = this.createElement('input');
  4012. toggle.checkbox.setAttribute('type', 'checkbox');
  4013. toggle.checkbox.setAttribute('data', name);
  4014. toggle.checkbox.addEventListener('change', (e) => {
  4015. const name = e.target.getAttribute('data');
  4016. this._state[name] = e.target.checked;
  4017. const toggle = this._toggles[name];
  4018. toggle.element.setAttribute('title', e.target.checked ? toggle.hide : toggle.show);
  4019. this.emit('state-changed', this._state);
  4020. this._update();
  4021. });
  4022. toggle.element.insertBefore(toggle.checkbox, toggle.element.firstChild);
  4023. this._search.appendChild(toggle.element);
  4024. }
  4025. this._content.addEventListener('click', (e) => {
  4026. if (this._table.has(e.target)) {
  4027. this.emit('select', this._table.get(e.target));
  4028. }
  4029. });
  4030. this._content.addEventListener('dblclick', (e) => {
  4031. if (this._table.has(e.target)) {
  4032. this.emit('activate', this._table.get(e.target));
  4033. }
  4034. });
  4035. this._content.addEventListener('pointerover', (e) => {
  4036. for (const element of this._focused) {
  4037. this._blur(element);
  4038. }
  4039. this._focus(e.target);
  4040. });
  4041. }
  4042. get element() {
  4043. return [this._search, this._content];
  4044. }
  4045. activate() {
  4046. this._query.focus();
  4047. this._query.value = '';
  4048. this._query.value = this._state.query;
  4049. for (const [name, toggle] of Object.entries(this._toggles)) {
  4050. toggle.checkbox.checked = this._state[name];
  4051. toggle.element.setAttribute('title', this._state[name] ? toggle.hide : toggle.show);
  4052. }
  4053. this._update();
  4054. this._host.event('open_sidebar', {
  4055. sidebar_identifier: this.identifier,
  4056. sidebar_size: this._table.size
  4057. });
  4058. }
  4059. deactivate() {
  4060. this._reset();
  4061. }
  4062. error(error, fatal) {
  4063. super.error(error, fatal);
  4064. const element = this.createElement('li');
  4065. const title = document.createElement('b');
  4066. title.textContent = 'ERROR: ';
  4067. element.appendChild(title);
  4068. const message = document.createTextNode(` ${error.message}`);
  4069. element.appendChild(message);
  4070. this._content.appendChild(element);
  4071. }
  4072. };
  4073. view.Quantization = class {
  4074. constructor(quantization) {
  4075. Object.assign(this, quantization);
  4076. }
  4077. toString() {
  4078. if (this.type === 'linear' || /^quant\d\d?_.*$/.test(this.type)) {
  4079. const content = [];
  4080. const scale = this.scale || [];
  4081. const offset = this.offset || [];
  4082. const bias = this.bias || [];
  4083. const max = this.max || [];
  4084. const min = this.min || [];
  4085. const length = Math.max(scale.length, offset.length, bias.length, min.length, max.length);
  4086. const size = length.toString().length;
  4087. for (let i = 0; i < length; i++) {
  4088. let s = 'q';
  4089. let bracket = false;
  4090. if (i < offset.length && offset[i] !== undefined && offset[i] !== 0 && offset[i] !== 0n) {
  4091. const value = offset[i];
  4092. s = value > 0 ? `${s} - ${value}` : `${s} + ${-value}`;
  4093. bracket = true;
  4094. }
  4095. if (i < scale.length && scale[i] !== undefined && scale[i] !== 1 && scale[i] !== 1n) {
  4096. const value = scale[i];
  4097. s = bracket ? `(${s})` : s;
  4098. s = `${value} * ${s}`;
  4099. bracket = true;
  4100. }
  4101. if (i < bias.length && bias[i] !== undefined && bias[i] !== 0 && bias[i] !== 0n) {
  4102. const value = bias[i];
  4103. s = bracket ? `(${s})` : s;
  4104. s = value < 0 ? `${s} - ${-value}` : `${s} + ${value}`;
  4105. }
  4106. if (i < min.length && min[i] !== undefined && min[i] !== 0 && min[i] !== 0n) {
  4107. s = `${min[i]} \u2264 ${s}`;
  4108. }
  4109. if (i < max.length && max[i] !== undefined && max[i] !== 0 && max[i] !== 0n) {
  4110. s = `${s} \u2264 ${max[i]}`;
  4111. }
  4112. content.push(length > 1 ? `${i.toString().padStart(size, ' ')}: ${s}` : `${s}`);
  4113. }
  4114. return content.join('\n');
  4115. } else if (this.type === 'lookup') {
  4116. const size = this.value.length.toString().length;
  4117. return this.value.map((value, index) => `${index.toString().padStart(size, ' ')}: ${value}`).join('\n');
  4118. } else if (this.type === 'annotation') {
  4119. return Array.from(this.value).map(([name, value]) => `${name} = ${value}`).join('\n');
  4120. } else if (/^q\d_[01k]$/.test(this.type) || /^iq\d_[xsnlm]+$/.test(this.type) || this.type === 'mxfp4') {
  4121. return '';
  4122. }
  4123. throw new view.Error(`Unknown quantization type '${this.type}'.`);
  4124. }
  4125. };
  4126. view.Documentation = class {
  4127. static open(source) {
  4128. if (source) {
  4129. const generator = markdown.Generator.open();
  4130. const target = {};
  4131. if (source.name) {
  4132. target.name = source.name;
  4133. }
  4134. if (source.module) {
  4135. target.module = source.module;
  4136. }
  4137. if (source.category) {
  4138. target.category = source.category;
  4139. }
  4140. if (source.summary) {
  4141. target.summary = generator.html(source.summary);
  4142. }
  4143. if (source.description) {
  4144. target.description = generator.html(source.description);
  4145. }
  4146. if (Array.isArray(source.attributes)) {
  4147. target.attributes = source.attributes.map((source) => {
  4148. const target = {};
  4149. target.name = source.name;
  4150. if (source.type !== undefined) {
  4151. target.type = source.type;
  4152. }
  4153. if (source.option !== undefined) {
  4154. target.option = source.option;
  4155. }
  4156. if (source.optional !== undefined) {
  4157. target.optional = source.optional;
  4158. }
  4159. if (source.required !== undefined) {
  4160. target.required = source.required;
  4161. }
  4162. if (source.minimum !== undefined) {
  4163. target.minimum = source.minimum;
  4164. }
  4165. if (source.src !== undefined) {
  4166. target.src = source.src;
  4167. }
  4168. if (source.src_type !== undefined) {
  4169. target.src_type = source.src_type;
  4170. }
  4171. if (source.description) {
  4172. target.description = generator.html(source.description);
  4173. }
  4174. if (source.default !== undefined) {
  4175. target.default = source.default;
  4176. }
  4177. if (source.visible !== undefined) {
  4178. target.visible = source.visible;
  4179. }
  4180. return target;
  4181. });
  4182. }
  4183. if (Array.isArray(source.inputs)) {
  4184. target.inputs = source.inputs.map((source) => {
  4185. const target = {};
  4186. target.name = source.name;
  4187. if (source.type !== undefined) {
  4188. target.type = source.type;
  4189. }
  4190. if (source.description) {
  4191. target.description = generator.html(source.description);
  4192. }
  4193. if (source.default !== undefined) {
  4194. target.default = source.default;
  4195. }
  4196. if (source.src !== undefined) {
  4197. target.src = source.src;
  4198. }
  4199. if (source.list !== undefined) {
  4200. target.list = source.list;
  4201. }
  4202. if (source.isRef !== undefined) {
  4203. target.isRef = source.isRef;
  4204. }
  4205. if (source.typeAttr !== undefined) {
  4206. target.typeAttr = source.typeAttr;
  4207. }
  4208. if (source.numberAttr !== undefined) {
  4209. target.numberAttr = source.numberAttr;
  4210. }
  4211. if (source.typeListAttr !== undefined) {
  4212. target.typeListAttr = source.typeListAttr;
  4213. }
  4214. if (source.option !== undefined) {
  4215. target.option = source.option;
  4216. }
  4217. if (source.optional !== undefined) {
  4218. target.optional = source.optional;
  4219. }
  4220. if (source.visible !== undefined) {
  4221. target.visible = source.visible;
  4222. }
  4223. return target;
  4224. });
  4225. }
  4226. if (Array.isArray(source.outputs)) {
  4227. target.outputs = source.outputs.map((source) => {
  4228. const target = {};
  4229. target.name = source.name;
  4230. if (source.type) {
  4231. target.type = source.type;
  4232. }
  4233. if (source.description) {
  4234. target.description = generator.html(source.description);
  4235. }
  4236. if (source.list !== undefined) {
  4237. target.list = source.list;
  4238. }
  4239. if (source.typeAttr !== undefined) {
  4240. target.typeAttr = source.typeAttr;
  4241. }
  4242. if (source.typeListAttr !== undefined) {
  4243. target.typeListAttr = source.typeListAttr;
  4244. }
  4245. if (source.numberAttr !== undefined) {
  4246. target.numberAttr = source.numberAttr;
  4247. }
  4248. if (source.isRef !== undefined) {
  4249. target.isRef = source.isRef;
  4250. }
  4251. if (source.option !== undefined) {
  4252. target.option = source.option;
  4253. }
  4254. return target;
  4255. });
  4256. }
  4257. if (Array.isArray(source.references)) {
  4258. target.references = source.references.map((source) => {
  4259. if (source) {
  4260. target.description = generator.html(source.description);
  4261. }
  4262. return target;
  4263. });
  4264. }
  4265. if (source.version !== undefined) {
  4266. target.version = source.version;
  4267. }
  4268. if (source.operator !== undefined) {
  4269. target.operator = source.operator;
  4270. }
  4271. if (source.identifier !== undefined) {
  4272. target.identifier = source.identifier;
  4273. }
  4274. if (source.package !== undefined) {
  4275. target.package = source.package;
  4276. }
  4277. if (source.status !== undefined) {
  4278. target.status = source.status;
  4279. }
  4280. if (source.min_input !== undefined) {
  4281. target.min_input = source.min_input;
  4282. }
  4283. if (source.max_input !== undefined) {
  4284. target.max_input = source.max_input;
  4285. }
  4286. if (source.min_output !== undefined) {
  4287. target.min_output = source.min_output;
  4288. }
  4289. if (source.max_output !== undefined) {
  4290. target.max_output = source.max_output;
  4291. }
  4292. if (source.inputs_range !== undefined) {
  4293. target.inputs_range = source.inputs_range;
  4294. }
  4295. if (source.outputs_range !== undefined) {
  4296. target.outputs_range = source.outputs_range;
  4297. }
  4298. if (source.examples !== undefined) {
  4299. target.examples = source.examples;
  4300. }
  4301. if (source.constants !== undefined) {
  4302. target.constants = source.constants;
  4303. }
  4304. if (source.type_constraints !== undefined) {
  4305. target.type_constraints = source.type_constraints;
  4306. }
  4307. return target;
  4308. }
  4309. return null;
  4310. }
  4311. };
  4312. view.Formatter = class {
  4313. constructor(value, type, quote) {
  4314. this._value = value;
  4315. this._type = type;
  4316. this._quote = quote;
  4317. this._values = new Set();
  4318. }
  4319. toString() {
  4320. return this._format(this._value, this._type, this._quote);
  4321. }
  4322. _format(value, type, quote) {
  4323. if (value && value.__class__ && value.__class__.__module__ === 'builtins' && value.__class__.__name__ === 'type') {
  4324. return `${value.__module__}.${value.__name__}`;
  4325. }
  4326. if (value && value.__class__ && value.__class__.__module__ === 'builtins' && value.__class__.__name__ === 'function') {
  4327. return `${value.__module__}.${value.__name__}`;
  4328. }
  4329. if (typeof value === 'function') {
  4330. return value();
  4331. }
  4332. if (value !== null && value !== undefined && (typeof value === 'bigint' || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')) {
  4333. return value.toString();
  4334. }
  4335. if (Number.isNaN(value)) {
  4336. return 'NaN';
  4337. }
  4338. switch (type) {
  4339. case 'shape':
  4340. return value ? value.toString() : '(null)';
  4341. case 'shape[]':
  4342. if (value && !Array.isArray(value)) {
  4343. throw new Error(`Invalid shape '${JSON.stringify(value)}'.`);
  4344. }
  4345. return value ? value.map((item) => item.toString()).join(', ') : '(null)';
  4346. case 'graph':
  4347. return value ? value.name : '(null)';
  4348. case 'graph[]':
  4349. return value ? value.map((graph) => graph.name).join(', ') : '(null)';
  4350. case 'tensor': {
  4351. if (value === null) {
  4352. return '(null)';
  4353. }
  4354. return view.Formatter.tensor(value);
  4355. }
  4356. case 'object':
  4357. case 'function':
  4358. return value.type.name;
  4359. case 'object[]':
  4360. case 'function[]':
  4361. return value ? value.map((item) => item.type.name).join(', ') : '(null)';
  4362. case 'type':
  4363. return value ? value.toString() : '(null)';
  4364. case 'type[]':
  4365. return value ? value.map((item) => item.toString()).join(', ') : '(null)';
  4366. default:
  4367. break;
  4368. }
  4369. if (typeof value === 'string' && (!type || type !== 'string')) {
  4370. if (quote) {
  4371. return `"${value}"`;
  4372. }
  4373. if (value.trim().length === 0) {
  4374. return '&nbsp;';
  4375. }
  4376. return value;
  4377. }
  4378. if (Array.isArray(value)) {
  4379. if (value.length === 0) {
  4380. return quote ? '[]' : '';
  4381. }
  4382. let ellipsis = false;
  4383. if (value.length > 1000) {
  4384. value = value.slice(0, 1000);
  4385. ellipsis = true;
  4386. }
  4387. const itemType = (type && type.endsWith('[]')) ? type.substring(0, type.length - 2) : null;
  4388. const array = value.map((value) => {
  4389. if (value && typeof value === 'bigint') {
  4390. return value.toString();
  4391. }
  4392. if (Number.isNaN(value)) {
  4393. return 'NaN';
  4394. }
  4395. if (value && value.constructor && value.constructor.name === 'Value' && value.name) {
  4396. return `{${value.name}}`;
  4397. }
  4398. const quote = !itemType || itemType === 'string';
  4399. return this._format(value, itemType, quote);
  4400. });
  4401. if (ellipsis) {
  4402. array.push('\u2026');
  4403. }
  4404. return quote ? ['[', array.join(', '), ']'].join(' ') : array.join(', ');
  4405. }
  4406. if (value === null) {
  4407. return quote ? 'null' : '';
  4408. }
  4409. if (value === undefined) {
  4410. return 'undefined';
  4411. }
  4412. if (value !== Object(value)) {
  4413. return value.toString();
  4414. }
  4415. if (this._values.has(value)) {
  4416. return '\u2026';
  4417. }
  4418. this._values.add(value);
  4419. let list = null;
  4420. const map = value instanceof Map ? Array.from(value) : Object.entries(value);
  4421. const entries = map.filter(([name]) => typeof name === 'string' && !name.startsWith('__') && !name.endsWith('__'));
  4422. if (entries.length === 1) {
  4423. list = [this._format(entries[0][1], null, true)];
  4424. } else {
  4425. list = entries.map(([name, value]) => `${name}: ${this._format(value, null, true)}`);
  4426. }
  4427. let objectType = value.__type__;
  4428. if (!objectType && value.constructor.name && value.constructor.name !== 'Object') {
  4429. objectType = value.constructor.name;
  4430. }
  4431. if (objectType) {
  4432. return objectType + (list.length === 0 ? '()' : ['(', list.join(', '), ')'].join(''));
  4433. }
  4434. switch (list.length) {
  4435. case 0:
  4436. return quote ? '()' : '';
  4437. case 1:
  4438. return list[0];
  4439. default:
  4440. return quote ? ['(', list.join(', '), ')'].join(' ') : list.join(', ');
  4441. }
  4442. }
  4443. static tensor(value) {
  4444. const type = value.type;
  4445. if (type && type.shape && type.shape.dimensions && Array.isArray(type.shape.dimensions)) {
  4446. if (type.shape.dimensions.length === 0 && (!value.peek || value.peek() === true)) {
  4447. const tensor = new base.Tensor(value);
  4448. const encoding = tensor.encoding;
  4449. if ((encoding === '<' || encoding === '>' || encoding === '|') && !tensor.empty && tensor.type.dataType !== '?') {
  4450. let content = tensor.toString();
  4451. if (content && content.length > 10) {
  4452. content = `${content.substring(0, 10)}\u2026`;
  4453. }
  4454. return content;
  4455. }
  4456. }
  4457. const content = type.shape.dimensions.map((d) => (d !== null && d !== undefined) ? d : '?').join('\u00D7');
  4458. return `\u3008${content}\u3009`;
  4459. }
  4460. return '\u3008\u2026\u3009';
  4461. }
  4462. };
  4463. markdown.Generator = class {
  4464. static open() {
  4465. if (!markdown.Generator.generator) {
  4466. markdown.Generator.generator = new markdown.Generator();
  4467. }
  4468. return markdown.Generator.generator;
  4469. }
  4470. constructor() {
  4471. this._newlineRegExp = /^\n+/;
  4472. this._codeRegExp = /^( {4}[^\n]+\n*)+/;
  4473. this._fencesRegExp = /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/;
  4474. this._hrRegExp = /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/;
  4475. this._headingRegExp = /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/;
  4476. this._blockquoteRegExp = /^( {0,3}> ?(([^\n]+(?:\n(?! {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)|[^\n]*)(?:\n|$))+/;
  4477. this._listRegExp = /^( {0,3})((?:[*+-]|\d{1,9}[.)])) [\s\S]+?(?:\n+(?=\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$))|\n+(?= {0,3}\[((?!\s*\])(?:\\[[\]]|[^[\]])+)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)((?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))))? *(?:\n+|$))|\n{2,}(?! )(?!\1(?:[*+-]|\d{1,9}[.)]) )\n*|\s*$)/;
  4478. this._htmlRegExp = /^ {0,3}(?:<(script|pre|style)[\s>][\s\S]*?(?:<\/\1>[^\n]*\n+|$)|<!--(?!-?>)[\s\S]*?(?:-->|$)[^\n]*(\n+|$)|<\?[\s\S]*?(?:\?>\n*|$)|<![A-Z][\s\S]*?(?:>\n*|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>\n*|$)|<\/?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)[\s\S]*?(?:\n{2,}|$)|<(?!script|pre|style)([a-z][\w-]*)(?: +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?)*? *\/?>(?=[ \t]*(?:\n|$))[\s\S]*?(?:\n{2,}|$)|<\/(?!script|pre|style)[a-z][\w-]*\s*>(?=[ \t]*(?:\n|$))[\s\S]*?(?:\n{2,}|$))/i;
  4479. this._defRegExp = /^ {0,3}\[((?!\s*\])(?:\\[[\]]|[^[\]])+)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)((?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))))? *(?:\n+|$)/;
  4480. this._nptableRegExp = /^ *([^|\n ].*\|.*)\n {0,3}([-:]+ *\|[-| :]*)(?:\n((?:(?!\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\n]| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--)).*(?:\n|$))*)\n*|$)/;
  4481. this._tableRegExp = /^ *\|(.+)\n {0,3}\|?( *[-:]+[-| :]*)(?:\n *((?:(?!\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\n]| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--)).*(?:\n|$))*)\n*|$)/;
  4482. this._lheadingRegExp = /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/;
  4483. this._textRegExp = /^[^\n]+/;
  4484. this._bulletRegExp = /(?:[*+-]|\d{1,9}[.)])/;
  4485. this._itemRegExp = /^( *)((?:[*+-]|\d{1,9}[.)])) ?[^\n]*(?:\n(?!\1(?:[*+-]|\d{1,9}[.)]) ?)[^\n]*)*/gm;
  4486. this._paragraphRegExp = /^([^\n]+(?:\n(?! {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/;
  4487. this._backpedalRegExp = /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/;
  4488. this._escapeRegExp = /^\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~~|])/;
  4489. this._escapesRegExp = /\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g;
  4490. /* eslint-disable no-control-regex */
  4491. this._autolinkRegExp = /^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s\x00-\x1f<>]*|[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_]))>/;
  4492. this._linkRegExp = /^!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\(\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)(?:\s+("(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)))?\s*\)/;
  4493. /* eslint-enable no-control-regex */
  4494. this._urlRegExp = /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9-]+\.?)+[^\s<]*|^[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/i;
  4495. this._tagRegExp = /^<!--(?!-?>)[\s\S]*?-->|^<\/[a-zA-Z][\w:-]*\s*>|^<[a-zA-Z][\w-]*(?:\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?)*?\s*\/?>|^<\?[\s\S]*?\?>|^<![a-zA-Z]+\s[\s\S]*?>|^<!\[CDATA\[[\s\S]*?\]\]>/;
  4496. this._reflinkRegExp = /^!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\[(?!\s*\])((?:\\[[\]]?|[^[\]\\])+)\]/;
  4497. this._nolinkRegExp = /^!?\[(?!\s*\])((?:\[[^[\]]*\]|\\[[\]]|[^[\]])*)\](?:\[\])?/;
  4498. this._reflinkSearchRegExp = /!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\[(?!\s*\])((?:\\[[\]]?|[^[\]\\])+)\]|!?\[(?!\s*\])((?:\[[^[\]]*\]|\\[[\]]|[^[\]])*)\](?:\[\])?(?!\()/g;
  4499. this._strongStartRegExp = /^(?:(\*\*(?=[*!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]))|\*\*)(?![\s])|__/;
  4500. this._strongMiddleRegExp = /^\*\*(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|\*(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?\*)+?\*\*$|^__(?![\s])((?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|_(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?_)+?)__$/;
  4501. this._strongEndAstRegExp = /[^!"#$%&'()+\-.,/:;<=>?@[\]`{|}~\s]\*\*(?!\*)|[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]\*\*(?!\*)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~_\s]|$))/g;
  4502. this._strongEndUndRegExp = /[^\s]__(?!_)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~*\s])|$)/g;
  4503. this._emStartRegExp = /^(?:(\*(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]))|\*)(?![*\s])|_/;
  4504. this._emMiddleRegExp = /^\*(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|\*(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?\*)+?\*$|^_(?![_\s])(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|_(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?_)+?_$/;
  4505. this._emEndAstRegExp = /[^!"#$%&'()+\-.,/:;<=>?@[\]`{|}~\s]\*(?!\*)|[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]\*(?!\*)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~_\s]|$))/g;
  4506. this._emEndUndRegExp = /[^\s]_(?!_)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~*\s])|$)/g;
  4507. this._codespanRegExp = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
  4508. this._brRegExp = /^( {2,}|\\)\n(?!\s*$)/;
  4509. this._delRegExp = /^~+(?=\S)([\s\S]*?\S)~+/;
  4510. this._textspanRegExp = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<![`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+/=?_`{|}~-](?=[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+@))|(?=[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+@))/;
  4511. this._punctuationRegExp = /^([\s*!"#$%&'()+\-.,/:;<=>?@[\]`{|}~])/;
  4512. this._blockSkipRegExp = /\[[^\]]*?\]\([^)]*?\)|`[^`]*?`|<[^>]*?>/g;
  4513. this._escapeTestRegExp = /[&<>"']/;
  4514. this._escapeReplaceRegExp = /[&<>"']/g;
  4515. this._escapeTestNoEncodeRegExp = /[<>"']|&(?!#?\w+;)/;
  4516. this._escapeReplaceNoEncodeRegExp = /[<>"']|&(?!#?\w+;)/g;
  4517. this._escapeReplacementsMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
  4518. this._cache = new Map();
  4519. }
  4520. html(source) {
  4521. if (this._cache.has(source)) {
  4522. return this._cache.get(source);
  4523. }
  4524. const tokens = [];
  4525. const links = new Map();
  4526. source = source.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' ');
  4527. this._tokenize(source, tokens, links, true);
  4528. this._tokenizeBlock(tokens, links);
  4529. const target = this._render(tokens, true);
  4530. if (this._cache.size > 256) {
  4531. this._cache.delete(this._cache.keys().next().value);
  4532. }
  4533. this._cache.set(source, target);
  4534. return target;
  4535. }
  4536. _tokenize(source, tokens, links, top) {
  4537. source = source.replace(/^ +$/gm, '');
  4538. while (source) {
  4539. let match = this._newlineRegExp.exec(source);
  4540. if (match) {
  4541. source = source.substring(match[0].length);
  4542. if (match[0].length > 1) {
  4543. tokens.push({ type: 'space' });
  4544. }
  4545. continue;
  4546. }
  4547. match = this._codeRegExp.exec(source);
  4548. if (match) {
  4549. source = source.substring(match[0].length);
  4550. const lastToken = tokens[tokens.length - 1];
  4551. if (lastToken && lastToken.type === 'paragraph') {
  4552. lastToken.text += `\n${match[0].trimRight()}`;
  4553. } else {
  4554. const text = match[0].replace(/^ {4}/gm, '').replace(/\n*$/, '');
  4555. tokens.push({ type: 'code', text });
  4556. }
  4557. continue;
  4558. }
  4559. match = this._fencesRegExp.exec(source);
  4560. if (match) {
  4561. source = source.substring(match[0].length);
  4562. const language = match[2] ? match[2].trim() : match[2];
  4563. let content = match[3] || '';
  4564. const matchIndent = match[0].match(/^(\s+)(?:```)/);
  4565. if (matchIndent !== null) {
  4566. const [, indent] = matchIndent;
  4567. content = content.split('\n').map((node) => {
  4568. const match = node.match(/^\s+/);
  4569. return (match !== null && match[0].length >= indent.length) ? node.slice(indent.length) : node;
  4570. }).join('\n');
  4571. }
  4572. tokens.push({ type: 'code', language, text: content });
  4573. continue;
  4574. }
  4575. match = this._headingRegExp.exec(source);
  4576. if (match) {
  4577. source = source.substring(match[0].length);
  4578. tokens.push({ type: 'heading', depth: match[1].length, text: match[2] });
  4579. continue;
  4580. }
  4581. match = this._nptableRegExp.exec(source);
  4582. if (match) {
  4583. const header = this._splitCells(match[1].replace(/^ *| *\| *$/g, ''));
  4584. const align = match[2].replace(/^ *|\| *$/g, '').split(/ *\| */);
  4585. if (header.length === align.length) {
  4586. const cells = match[3] ? match[3].replace(/\n$/, '').split('\n') : [];
  4587. const token = { type: 'table', header, align, cells, raw: match[0] };
  4588. for (let i = 0; i < token.align.length; i++) {
  4589. if (/^ *-+: *$/.test(token.align[i])) {
  4590. token.align[i] = 'right';
  4591. } else if (/^ *:-+: *$/.test(token.align[i])) {
  4592. token.align[i] = 'center';
  4593. } else if (/^ *:-+ *$/.test(token.align[i])) {
  4594. token.align[i] = 'left';
  4595. } else {
  4596. token.align[i] = null;
  4597. }
  4598. }
  4599. token.cells = token.cells.map((cell) => this._splitCells(cell, token.header.length));
  4600. source = source.substring(token.raw.length);
  4601. tokens.push(token);
  4602. continue;
  4603. }
  4604. }
  4605. match = this._hrRegExp.exec(source);
  4606. if (match) {
  4607. source = source.substring(match[0].length);
  4608. tokens.push({ type: 'hr' });
  4609. continue;
  4610. }
  4611. match = this._blockquoteRegExp.exec(source);
  4612. if (match) {
  4613. source = source.substring(match[0].length);
  4614. const text = match[0].replace(/^ *> ?/gm, '');
  4615. tokens.push({ type: 'blockquote', text, tokens: this._tokenize(text, [], links, top) });
  4616. continue;
  4617. }
  4618. match = this._listRegExp.exec(source);
  4619. if (match) {
  4620. const [value, , bull] = match;
  4621. const ordered = bull.length > 1;
  4622. const parent = bull[bull.length - 1] === ')';
  4623. let raw = value;
  4624. const list = { type: 'list', raw, ordered, start: ordered ? Number(bull.slice(0, -1)) : '', loose: false, items: [] };
  4625. const itemMatch = value.match(this._itemRegExp);
  4626. let next = false;
  4627. const length = itemMatch.length;
  4628. for (let i = 0; i < length; i++) {
  4629. let item = itemMatch[i];
  4630. raw = item;
  4631. let space = item.length;
  4632. item = item.replace(/^ *([*+-]|\d+[.)]) ?/, '');
  4633. if (item.indexOf('\n ') !== -1) {
  4634. space -= item.length;
  4635. item = item.replace(new RegExp(`^ {1,${space}}`, 'gm'), '');
  4636. }
  4637. if (i !== length - 1) {
  4638. const [bullet] = this._bulletRegExp.exec(itemMatch[i + 1]);
  4639. if (ordered ? bullet.length === 1 || (!parent && bullet[bullet.length - 1] === ')') : (bullet.length > 1)) {
  4640. const addBack = itemMatch.slice(i + 1).join('\n');
  4641. list.raw = list.raw.substring(0, list.raw.length - addBack.length);
  4642. i = length - 1;
  4643. }
  4644. }
  4645. let loose = next || /\n\n(?!\s*$)/.test(item);
  4646. if (i !== length - 1) {
  4647. next = item.charAt(item.length - 1) === '\n';
  4648. if (!loose) {
  4649. loose = next;
  4650. }
  4651. }
  4652. if (loose) {
  4653. list.loose = true;
  4654. }
  4655. const task = /^\[[ xX]\] /.test(item);
  4656. let checked = false;
  4657. if (task) {
  4658. checked = item[1] !== ' ';
  4659. item = item.replace(/^\[[ xX]\] +/, '');
  4660. }
  4661. list.items.push({ type: 'list_item', raw, task, checked, loose, text: item });
  4662. }
  4663. source = source.substring(list.raw.length);
  4664. for (const item of list.items) {
  4665. item.tokens = this._tokenize(item.text, [], links, false);
  4666. }
  4667. tokens.push(list);
  4668. continue;
  4669. }
  4670. match = this._htmlRegExp.exec(source);
  4671. if (match) {
  4672. source = source.substring(match[0].length);
  4673. tokens.push({ type: 'html', pre: (match[1] === 'pre' || match[1] === 'script' || match[1] === 'style'), text: match[0] });
  4674. continue;
  4675. }
  4676. if (top) {
  4677. match = this._defRegExp.exec(source);
  4678. if (match) {
  4679. source = source.substring(match[0].length);
  4680. match[3] = match[3] ? match[3].substring(1, match[3].length - 1) : match[3];
  4681. const tag = match[1].toLowerCase().replace(/\s+/g, ' ');
  4682. if (!links.has(tag)) {
  4683. links.set(tag, { href: match[2], title: match[3] });
  4684. }
  4685. continue;
  4686. }
  4687. }
  4688. match = this._tableRegExp.exec(source);
  4689. if (match) {
  4690. const header = this._splitCells(match[1].replace(/^ *| *\| *$/g, ''));
  4691. const align = match[2].replace(/^ *|\| *$/g, '').split(/ *\| */);
  4692. if (header.length === align.length) {
  4693. const cells = match[3] ? match[3].replace(/\n$/, '').split('\n') : [];
  4694. const token = { type: 'table', header, align, cells, raw: match[0] };
  4695. for (let i = 0; i < token.align.length; i++) {
  4696. if (/^ *-+: *$/.test(token.align[i])) {
  4697. token.align[i] = 'right';
  4698. } else if (/^ *:-+: *$/.test(token.align[i])) {
  4699. token.align[i] = 'center';
  4700. } else if (/^ *:-+ *$/.test(token.align[i])) {
  4701. token.align[i] = 'left';
  4702. } else {
  4703. token.align[i] = null;
  4704. }
  4705. }
  4706. token.cells = token.cells.map((cell) => this._splitCells(cell.replace(/^ *\| *| *\| *$/g, ''), token.header.length));
  4707. source = source.substring(token.raw.length);
  4708. tokens.push(token);
  4709. continue;
  4710. }
  4711. }
  4712. match = this._lheadingRegExp.exec(source);
  4713. if (match) {
  4714. source = source.substring(match[0].length);
  4715. tokens.push({ type: 'heading', depth: match[2].charAt(0) === '=' ? 1 : 2, text: match[1] });
  4716. continue;
  4717. }
  4718. if (top) {
  4719. match = this._paragraphRegExp.exec(source);
  4720. if (match) {
  4721. source = source.substring(match[0].length);
  4722. tokens.push({ type: 'paragraph', text: match[1].charAt(match[1].length - 1) === '\n' ? match[1].slice(0, -1) : match[1] });
  4723. continue;
  4724. }
  4725. }
  4726. match = this._textRegExp.exec(source);
  4727. if (match) {
  4728. source = source.substring(match[0].length);
  4729. const lastToken = tokens[tokens.length - 1];
  4730. if (lastToken && lastToken.type === 'text') {
  4731. lastToken.text += `\n${match[0]}`;
  4732. } else {
  4733. tokens.push({ type: 'text', text: match[0] });
  4734. }
  4735. continue;
  4736. }
  4737. throw new Error(`Unexpected '${source.charCodeAt(0)}'.`);
  4738. }
  4739. return tokens;
  4740. }
  4741. _tokenizeInline(source, links, inLink, inRawBlock, prevChar) {
  4742. const tokens = [];
  4743. let maskedSource = source;
  4744. if (links.size > 0) {
  4745. while (maskedSource) {
  4746. const match = this._reflinkSearchRegExp.exec(maskedSource);
  4747. if (match) {
  4748. if (links.has(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
  4749. maskedSource = `${maskedSource.slice(0, match.index)}[${'a'.repeat(match[0].length - 2)}]${maskedSource.slice(this._reflinkSearchRegExp.lastIndex)}`;
  4750. }
  4751. continue;
  4752. }
  4753. break;
  4754. }
  4755. }
  4756. while (maskedSource) {
  4757. const match = this._blockSkipRegExp.exec(maskedSource);
  4758. if (match) {
  4759. maskedSource = `${maskedSource.slice(0, match.index)}[${'a'.repeat(match[0].length - 2)}]${maskedSource.slice(this._blockSkipRegExp.lastIndex)}`;
  4760. continue;
  4761. }
  4762. break;
  4763. }
  4764. while (source) {
  4765. let match = this._escapeRegExp.exec(source);
  4766. if (match) {
  4767. source = source.substring(match[0].length);
  4768. tokens.push({ type: 'escape', text: this._escape(match[1]) });
  4769. continue;
  4770. }
  4771. match = this._tagRegExp.exec(source);
  4772. if (match) {
  4773. source = source.substring(match[0].length);
  4774. if (!inLink && /^<a /i.test(match[0])) {
  4775. inLink = true;
  4776. } else if (inLink && /^<\/a>/i.test(match[0])) {
  4777. inLink = false;
  4778. }
  4779. if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(match[0])) {
  4780. inRawBlock = true;
  4781. } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(match[0])) {
  4782. inRawBlock = false;
  4783. }
  4784. tokens.push({ type: 'html', raw: match[0], text: match[0] });
  4785. continue;
  4786. }
  4787. match = this._linkRegExp.exec(source);
  4788. if (match) {
  4789. let index = -1;
  4790. const [, , ref] = match;
  4791. if (ref.indexOf(')') !== -1) {
  4792. let level = 0;
  4793. for (let i = 0; i < ref.length; i++) {
  4794. switch (ref[i]) {
  4795. case '\\':
  4796. i++;
  4797. break;
  4798. case '(':
  4799. level++;
  4800. break;
  4801. case ')':
  4802. level--;
  4803. if (level < 0) {
  4804. index = i;
  4805. i = ref.length;
  4806. }
  4807. break;
  4808. default:
  4809. break;
  4810. }
  4811. }
  4812. }
  4813. if (index > -1) {
  4814. const length = (match[0].indexOf('!') === 0 ? 5 : 4) + match[1].length + index;
  4815. match[2] = match[2].substring(0, index);
  4816. match[0] = match[0].substring(0, length).trim();
  4817. match[3] = '';
  4818. }
  4819. const title = (match[3] ? match[3].slice(1, -1) : '').replace(this._escapesRegExp, '$1');
  4820. const href = match[2].trim().replace(/^<([\s\S]*)>$/, '$1').replace(this._escapesRegExp, '$1');
  4821. const token = this._outputLink(match, href, title);
  4822. source = source.substring(match[0].length);
  4823. if (token.type === 'link') {
  4824. token.tokens = this._tokenizeInline(token.text, links, true, inRawBlock, '');
  4825. }
  4826. tokens.push(token);
  4827. continue;
  4828. }
  4829. match = this._reflinkRegExp.exec(source) || this._nolinkRegExp.exec(source);
  4830. if (match) {
  4831. let link = (match[2] || match[1]).replace(/\s+/g, ' ');
  4832. link = links.get(link.toLowerCase());
  4833. if (!link || !link.href) {
  4834. const text = match[0].charAt(0);
  4835. source = source.substring(text.length);
  4836. tokens.push({ type: 'text', text });
  4837. } else {
  4838. source = source.substring(match[0].length);
  4839. const token = this._outputLink(match, link);
  4840. if (token.type === 'link') {
  4841. token.tokens = this._tokenizeInline(token.text, links, true, inRawBlock, '');
  4842. }
  4843. tokens.push(token);
  4844. }
  4845. continue;
  4846. }
  4847. match = this._strongStartRegExp.exec(source);
  4848. if (match && (!match[1] || (match[1] && (prevChar === '' || this._punctuationRegExp.exec(prevChar))))) {
  4849. const masked = maskedSource.slice(-1 * source.length);
  4850. const endReg = match[0] === '**' ? this._strongEndAstRegExp : this._strongEndUndRegExp;
  4851. endReg.lastIndex = 0;
  4852. let cap = '';
  4853. while ((match = endReg.exec(masked)) !== null) {
  4854. cap = this._strongMiddleRegExp.exec(masked.slice(0, match.index + 3));
  4855. if (cap) {
  4856. break;
  4857. }
  4858. }
  4859. if (cap) {
  4860. const text = source.substring(2, cap[0].length - 2);
  4861. source = source.substring(cap[0].length);
  4862. tokens.push({ type: 'strong', text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4863. continue;
  4864. }
  4865. }
  4866. match = this._emStartRegExp.exec(source);
  4867. if (match && (!match[1] || (match[1] && (prevChar === '' || this._punctuationRegExp.exec(prevChar))))) {
  4868. const masked = maskedSource.slice(-1 * source.length);
  4869. const endReg = match[0] === '*' ? this._emEndAstRegExp : this._emEndUndRegExp;
  4870. endReg.lastIndex = 0;
  4871. let cap = '';
  4872. while ((match = endReg.exec(masked)) !== null) {
  4873. cap = this._emMiddleRegExp.exec(masked.slice(0, match.index + 2));
  4874. if (cap) {
  4875. break;
  4876. }
  4877. }
  4878. if (cap) {
  4879. const text = source.slice(1, cap[0].length - 1);
  4880. source = source.substring(cap[0].length);
  4881. tokens.push({ type: 'em', text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4882. continue;
  4883. }
  4884. }
  4885. match = this._codespanRegExp.exec(source);
  4886. if (match) {
  4887. source = source.substring(match[0].length);
  4888. let content = match[2].replace(/\n/g, ' ');
  4889. if (/[^ ]/.test(content) && content.startsWith(' ') && content.endsWith(' ')) {
  4890. content = content.substring(1, content.length - 1);
  4891. }
  4892. tokens.push({ type: 'codespan', text: this._encode(content) });
  4893. continue;
  4894. }
  4895. match = this._brRegExp.exec(source);
  4896. if (match) {
  4897. source = source.substring(match[0].length);
  4898. tokens.push({ type: 'br' });
  4899. continue;
  4900. }
  4901. match = this._delRegExp.exec(source);
  4902. if (match) {
  4903. const [value, text] = match;
  4904. source = source.substring(value.length);
  4905. tokens.push({ type: 'del', text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4906. continue;
  4907. }
  4908. match = this._autolinkRegExp.exec(source);
  4909. if (match) {
  4910. source = source.substring(match[0].length);
  4911. const text = this._escape(match[1]);
  4912. const href = match[2] === '@' ? `mailto:${text}` : text;
  4913. tokens.push({ type: 'link', text, href, tokens: [{ type: 'text', raw: text, text }] });
  4914. continue;
  4915. }
  4916. if (!inLink) {
  4917. match = this._urlRegExp.exec(source);
  4918. if (match) {
  4919. const email = match[2] === '@';
  4920. let [value] = match;
  4921. if (!email) {
  4922. let prevCapZero = '';
  4923. do {
  4924. prevCapZero = value;
  4925. [value] = this._backpedalRegExp.exec(value);
  4926. } while (prevCapZero !== value);
  4927. }
  4928. const text = this._escape(value);
  4929. let href = text;
  4930. if (email) {
  4931. href = `mailto:${text}`;
  4932. } else if (text.startsWith('www.')) {
  4933. href = `http://${text}`;
  4934. }
  4935. source = source.substring(value.length);
  4936. tokens.push({ type: 'link', text, href, tokens: [{ type: 'text', text }] });
  4937. continue;
  4938. }
  4939. }
  4940. match = this._textspanRegExp.exec(source);
  4941. if (match) {
  4942. source = source.substring(match[0].length);
  4943. prevChar = match[0].slice(-1);
  4944. tokens.push({ type: 'text' , text: inRawBlock ? match[0] : this._escape(match[0]) });
  4945. continue;
  4946. }
  4947. throw new Error(`Unexpected '${source.charCodeAt(0)}'.`);
  4948. }
  4949. return tokens;
  4950. }
  4951. _tokenizeBlock(tokens, links) {
  4952. for (const token of tokens) {
  4953. switch (token.type) {
  4954. case 'paragraph':
  4955. case 'text':
  4956. case 'heading': {
  4957. token.tokens = this._tokenizeInline(token.text, links, false, false, '');
  4958. break;
  4959. }
  4960. case 'table': {
  4961. token.tokens = {};
  4962. token.tokens.header = token.header.map((header) => this._tokenizeInline(header, links, false, false, ''));
  4963. token.tokens.cells = token.cells.map((cell) => cell.map((row) => this._tokenizeInline(row, links, false, false, '')));
  4964. break;
  4965. }
  4966. case 'blockquote': {
  4967. this._tokenizeBlock(token.tokens, links);
  4968. break;
  4969. }
  4970. case 'list': {
  4971. for (const item of token.items) {
  4972. this._tokenizeBlock(item.tokens, links);
  4973. }
  4974. break;
  4975. }
  4976. default: {
  4977. break;
  4978. }
  4979. }
  4980. }
  4981. }
  4982. _render(tokens, top) {
  4983. let html = '';
  4984. while (tokens.length > 0) {
  4985. const token = tokens.shift();
  4986. switch (token.type) {
  4987. case 'space': {
  4988. continue;
  4989. }
  4990. case 'hr': {
  4991. html += '<hr>\n';
  4992. continue;
  4993. }
  4994. case 'heading': {
  4995. const level = token.depth;
  4996. html += `<h${level}">${this._renderInline(token.tokens)}</h${level}>\n`;
  4997. continue;
  4998. }
  4999. case 'code': {
  5000. const code = token.text;
  5001. const [language] = (token.language || '').match(/\S*/);
  5002. html += `<pre><code${language ? ` class="language-${this._encode(language)}"` : ''}>${token.escaped ? code : this._encode(code)}</code></pre>\n`;
  5003. continue;
  5004. }
  5005. case 'table': {
  5006. let header = '';
  5007. let cell = '';
  5008. for (let j = 0; j < token.header.length; j++) {
  5009. const content = this._renderInline(token.tokens.header[j]);
  5010. const align = token.align[j];
  5011. cell += `<th${align ? ` align="${align}"` : ''}>${content}</th>\n`;
  5012. }
  5013. header += `<tr>\n${cell}</tr>\n`;
  5014. let body = '';
  5015. for (let j = 0; j < token.cells.length; j++) {
  5016. const row = token.tokens.cells[j];
  5017. cell = '';
  5018. for (let k = 0; k < row.length; k++) {
  5019. const content = this._renderInline(row[k]);
  5020. const align = token.align[k];
  5021. cell += `<td${align ? ` align="${align}"` : ''}>${content}</td>\n`;
  5022. }
  5023. body += `<tr>\n${cell}</tr>\n`;
  5024. }
  5025. html += `<table>\n<thead>\n${header}</thead>\n${body ? `<tbody>${body}</tbody>` : body}</table>\n`;
  5026. continue;
  5027. }
  5028. case 'blockquote': {
  5029. html += `<blockquote>\n${this._render(token.tokens, true)}</blockquote>\n`;
  5030. continue;
  5031. }
  5032. case 'list': {
  5033. const ordered = token.ordered;
  5034. const start = token.start;
  5035. const loose = token.loose;
  5036. let body = '';
  5037. for (const item of token.items) {
  5038. let itemBody = '';
  5039. if (item.task) {
  5040. const checkbox = `<input ${item.checked ? 'checked="" ' : ''}disabled="" type="checkbox"> `;
  5041. if (loose) {
  5042. if (item.tokens.length > 0 && item.tokens[0].type === 'text') {
  5043. item.tokens[0].text = `${checkbox} ${item.tokens[0].text}`;
  5044. if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
  5045. item.tokens[0].tokens[0].text = `${checkbox} ${item.tokens[0].tokens[0].text}`;
  5046. }
  5047. } else {
  5048. item.tokens.unshift({ type: 'text', text: checkbox });
  5049. }
  5050. } else {
  5051. itemBody += checkbox;
  5052. }
  5053. }
  5054. itemBody += this._render(item.tokens, loose);
  5055. body += `<li>${itemBody}</li>\n`;
  5056. }
  5057. const type = (ordered ? 'ol' : 'ul');
  5058. html += `<${type}${ordered && start !== 1 ? (` start="${start}"`) : ''}>\n${body}</${type}>\n`;
  5059. continue;
  5060. }
  5061. case 'html': {
  5062. html += token.text;
  5063. continue;
  5064. }
  5065. case 'paragraph': {
  5066. html += `<p>${this._renderInline(token.tokens)}</p>\n`;
  5067. continue;
  5068. }
  5069. case 'text': {
  5070. html += top ? '<p>' : '';
  5071. html += token.tokens ? this._renderInline(token.tokens) : token.text;
  5072. while (tokens.length > 0 && tokens[0].type === 'text') {
  5073. const token = tokens.shift();
  5074. html += `\n${token.tokens ? this._renderInline(token.tokens) : token.text}`;
  5075. }
  5076. html += top ? '</p>\n' : '';
  5077. continue;
  5078. }
  5079. default: {
  5080. throw new Error(`Unexpected token type '${token.type}'.`);
  5081. }
  5082. }
  5083. }
  5084. return html;
  5085. }
  5086. _renderInline(tokens) {
  5087. let html = '';
  5088. for (const token of tokens) {
  5089. switch (token.type) {
  5090. case 'escape':
  5091. case 'html':
  5092. case 'text': {
  5093. html += token.text;
  5094. break;
  5095. }
  5096. case 'link': {
  5097. const text = this._renderInline(token.tokens);
  5098. html += `<a href="${token.href}"${token.title ? ` title="${token.title}"` : ''} target="_blank">${text}</a>`;
  5099. break;
  5100. }
  5101. case 'image': {
  5102. html += `<img src="${token.href}" alt="${token.text}"${token.title ? ` title="${token.title}"` : ''}>`;
  5103. break;
  5104. }
  5105. case 'strong': {
  5106. const text = this._renderInline(token.tokens);
  5107. html += `<strong>${text}</strong>`;
  5108. break;
  5109. }
  5110. case 'em': {
  5111. const text = this._renderInline(token.tokens);
  5112. html += `<em>${text}</em>`;
  5113. break;
  5114. }
  5115. case 'codespan': {
  5116. html += `<code>${token.text}</code>`;
  5117. break;
  5118. }
  5119. case 'br': {
  5120. html += '<br>';
  5121. break;
  5122. }
  5123. case 'del': {
  5124. const text = this._renderInline(token.tokens);
  5125. html += `<del>${text}</del>`;
  5126. break;
  5127. }
  5128. default: {
  5129. throw new Error(`Unexpected token type '${token.type}'.`);
  5130. }
  5131. }
  5132. }
  5133. return html;
  5134. }
  5135. _outputLink(match, href, title) {
  5136. title = title ? this._escape(title) : null;
  5137. const text = match[1].replace(/\\([[\]])/g, '$1');
  5138. return match[0].charAt(0) === '!' ?
  5139. { type: 'image', href, title, text: this._escape(text) } :
  5140. { type: 'link', href, title, text };
  5141. }
  5142. _splitCells(tableRow, count) {
  5143. const row = tableRow.replace(/\|/g, (match, offset, str) => {
  5144. let escaped = false;
  5145. let position = offset;
  5146. while (--position >= 0 && str[position] === '\\') {
  5147. escaped = !escaped;
  5148. }
  5149. return escaped ? '|' : ' |';
  5150. });
  5151. const cells = row.split(/ \|/);
  5152. if (cells.length > count) {
  5153. cells.splice(count);
  5154. } else {
  5155. while (cells.length < count) {
  5156. cells.push('');
  5157. }
  5158. }
  5159. return cells.map((cell) => cell.trim().replace(/\\\|/g, '|'));
  5160. }
  5161. _encode(content) {
  5162. if (this._escapeTestRegExp.test(content)) {
  5163. return content.replace(this._escapeReplaceRegExp, (ch) => this._escapeReplacementsMap[ch]);
  5164. }
  5165. return content;
  5166. }
  5167. _escape(content) {
  5168. if (this._escapeTestNoEncodeRegExp.test(content)) {
  5169. return content.replace(this._escapeReplaceNoEncodeRegExp, (ch) => this._escapeReplacementsMap[ch]);
  5170. }
  5171. return content;
  5172. }
  5173. };
  5174. metadata.Attachment = class {
  5175. constructor() {
  5176. this.metadata = new metadata.Attachment.Container('metadata');
  5177. this.metrics = new metadata.Attachment.Container('metrics');
  5178. }
  5179. async open(context) {
  5180. context = new view.Context(context);
  5181. if (context.identifier.toLowerCase().endsWith('.json')) {
  5182. const data = await context.peek('json');
  5183. if (data && data.signature === 'netron:attachment') {
  5184. const containers = [this.metadata, this.metrics];
  5185. for (const container of containers) {
  5186. container.open(data[container.name]);
  5187. }
  5188. return true;
  5189. }
  5190. }
  5191. return false;
  5192. }
  5193. };
  5194. metadata.Attachment.Container = class {
  5195. constructor(name) {
  5196. this._name = name;
  5197. this._entries = new Map();
  5198. }
  5199. get name() {
  5200. return this._name;
  5201. }
  5202. open(data) {
  5203. this._entries.clear();
  5204. if (Array.isArray(data)) {
  5205. for (const item of data) {
  5206. if (item.kind && ('target' in item || 'identifier' in item)) {
  5207. const key = 'target' in item ? `${item.kind}::${item.target}` : `${item.kind}[${item.identifier}]`;
  5208. if (!this._entries.has(key)) {
  5209. this._entries.set(key, new Map());
  5210. }
  5211. const entries = this._entries.get(key);
  5212. entries.set(item.name, { value: item.value, type: item.type });
  5213. }
  5214. }
  5215. }
  5216. }
  5217. model(value) {
  5218. return this._list(value, 'model');
  5219. }
  5220. graph(value) {
  5221. return this._list(value, 'graph');
  5222. }
  5223. node(value) {
  5224. return this._list(value, 'node');
  5225. }
  5226. value(value) {
  5227. return this._list(value, 'value');
  5228. }
  5229. tensor(value) {
  5230. return this._list(value, 'tensor');
  5231. }
  5232. _list(value, kind) {
  5233. const category = this._name;
  5234. const entries = value[category] || [];
  5235. const result = new Map(entries.map((entry) => [entry.name, entry]));
  5236. if (value.name || kind === 'model' || kind === 'graph') {
  5237. const key = `${kind}::${(value.name || '').split('\n').shift()}`;
  5238. if (this._entries.has(key)) {
  5239. for (const [name, entry] of this._entries.get(key)) {
  5240. const argument = new metadata.Argument(name, entry.value, entry.type || 'attribute');
  5241. result.set(name, argument);
  5242. }
  5243. }
  5244. }
  5245. if (value.identifier) {
  5246. const key = `${kind}[${value.identifier}]`;
  5247. if (this._entries.has(key)) {
  5248. for (const [name, entry] of this._entries.get(key)) {
  5249. const argument = new metadata.Argument(name, entry.value, entry.type || 'attribute');
  5250. result.set(name, argument);
  5251. }
  5252. }
  5253. }
  5254. return Array.from(result.values());
  5255. }
  5256. };
  5257. metadata.Argument = class {
  5258. constructor(name, value, type) {
  5259. this.name = name;
  5260. this.value = value;
  5261. this.type = type;
  5262. }
  5263. };
  5264. metrics.Model = class {
  5265. constructor(model) {
  5266. this._model = model;
  5267. this._metrics = null;
  5268. }
  5269. get metrics() {
  5270. if (this._metrics === null) {
  5271. this._metrics = [];
  5272. this._metrics = Array.from(this._model.metrics || []);
  5273. const keys = new Set(this._metrics.map((metric) => metric.name));
  5274. if (!keys.has('parameters')) {
  5275. let parameters = 0;
  5276. for (const graph of this._model.graphs || []) {
  5277. const map = new Map((new metrics.Target(graph).metrics || []).map((metric) => [metric.name, metric]));
  5278. parameters = map.has('parameters') ? parameters + map.get('parameters').value : NaN;
  5279. }
  5280. for (const func of this._model.functions || []) {
  5281. const map = new Map((new metrics.Target(func).metrics || []).map((metric) => [metric.name, metric]));
  5282. parameters = map.has('parameters') ? parameters + map.get('parameters').value : NaN;
  5283. }
  5284. if (!Number.isNaN(parameters) && parameters > 0) {
  5285. this._metrics.push(new metadata.Argument('parameters', parameters, 'attribute'));
  5286. }
  5287. }
  5288. }
  5289. return this._metrics;
  5290. }
  5291. };
  5292. metrics.Target = class {
  5293. constructor(target) {
  5294. this._target = target;
  5295. this._metrics = null;
  5296. }
  5297. get metrics() {
  5298. if (this._metrics === null) {
  5299. this._metrics = [];
  5300. this._metrics = Array.from(this._target.metrics || []);
  5301. const keys = new Set(this._metrics.map((metrics) => metrics.name));
  5302. if (!keys.has('parameters')) {
  5303. let parameters = 0;
  5304. const initializers = new Set();
  5305. if (this._target && Array.isArray(this._target.nodes)) {
  5306. for (const node of this._target.nodes) {
  5307. for (const argument of node.inputs || []) {
  5308. if (argument && Array.isArray(argument.value)) {
  5309. for (const value of argument.value) {
  5310. if (value && value.initializer) {
  5311. initializers.add(value.initializer);
  5312. }
  5313. }
  5314. }
  5315. }
  5316. }
  5317. }
  5318. for (const tensor of initializers) {
  5319. const shape = tensor && tensor.type && tensor.type.shape && Array.isArray(tensor.type.shape.dimensions) ? tensor.type.shape.dimensions : [];
  5320. if (!shape.every((dim) => typeof dim === 'number')) {
  5321. parameters = 0;
  5322. break;
  5323. }
  5324. parameters += shape.reduce((a, b) => a * b, 1);
  5325. }
  5326. if (parameters > 0) {
  5327. this._metrics.push(new metadata.Argument('parameters', parameters, 'attribute'));
  5328. }
  5329. }
  5330. }
  5331. return this._metrics;
  5332. }
  5333. };
  5334. metrics.Tensor = class {
  5335. constructor(tensor) {
  5336. this._tensor = tensor;
  5337. this._metrics = null;
  5338. }
  5339. get name() {
  5340. return this._tensor.name || '';
  5341. }
  5342. get metrics() {
  5343. if (this._metrics === null) {
  5344. this._metrics = [];
  5345. this._metrics = Array.from(this._tensor.metrics || []);
  5346. const keys = new Set(this._metrics.map((metrics) => metrics.name));
  5347. const type = this._tensor.type;
  5348. const shape = type.shape.dimensions;
  5349. const size = shape.reduce((a, b) => a * b, 1);
  5350. if (size < 0x800000 &&
  5351. (type.dataType.startsWith('float') || type.dataType.startsWith('bfloat')) &&
  5352. (!keys.has('sparsity') || !keys.has('min') || !keys.has('max') && !keys.has('mean') || !keys.has('max') || !keys.has('std'))) {
  5353. const data = this._tensor.value;
  5354. let zeros = 0;
  5355. let min = null;
  5356. let max = null;
  5357. let sum = 0;
  5358. let count = 0;
  5359. const stack = [data];
  5360. while (stack.length > 0) {
  5361. const data = stack.pop();
  5362. if (Array.isArray(data)) {
  5363. for (const element of data) {
  5364. stack.push(element);
  5365. }
  5366. } else {
  5367. zeros += data === 0 || data === 0n || data === '';
  5368. min = Math.min(data, min === null ? data : min);
  5369. max = Math.max(data, max === null ? data : max);
  5370. sum += data;
  5371. count += 1;
  5372. }
  5373. }
  5374. const mean = sum / count;
  5375. if (!keys.has('sparsity')) {
  5376. this._metrics.push(new metadata.Argument('min', min, type.dataType));
  5377. }
  5378. if (!keys.has('max')) {
  5379. this._metrics.push(new metadata.Argument('max', max, type.dataType));
  5380. }
  5381. if (!keys.has('mean')) {
  5382. this._metrics.push(new metadata.Argument('mean', mean, type.dataType));
  5383. }
  5384. if (!keys.has('std')) {
  5385. let variance = 0;
  5386. const stack = [data];
  5387. while (stack.length > 0) {
  5388. const data = stack.pop();
  5389. if (Array.isArray(data)) {
  5390. for (const element of data) {
  5391. stack.push(element);
  5392. }
  5393. } else {
  5394. variance += Math.pow(data - mean, 2);
  5395. }
  5396. }
  5397. this._metrics.push(new metadata.Argument('std', Math.sqrt(variance / count)));
  5398. }
  5399. if (!keys.has('sparsity')) {
  5400. this._metrics.push(new metadata.Argument('sparsity', count > 0 ? zeros / count : 0, 'percentage'));
  5401. }
  5402. }
  5403. }
  5404. return this._metrics;
  5405. }
  5406. };
  5407. view.Context = class {
  5408. constructor(context, identifier, stream) {
  5409. this._context = context;
  5410. this._tags = new Map();
  5411. this._content = new Map();
  5412. this._stream = stream || context.stream;
  5413. identifier = typeof identifier === 'string' ? identifier : context.identifier;
  5414. const index = Math.max(identifier.lastIndexOf('/'), identifier.lastIndexOf('\\'));
  5415. this._base = index === -1 ? undefined : identifier.substring(0, index);
  5416. this._identifier = index === -1 ? identifier : identifier.substring(index + 1);
  5417. }
  5418. get identifier() {
  5419. return this._identifier;
  5420. }
  5421. get stream() {
  5422. return this._stream;
  5423. }
  5424. get container() {
  5425. if (this._context instanceof view.EntryContext) {
  5426. return this._context;
  5427. }
  5428. return null;
  5429. }
  5430. async request(file) {
  5431. return this._context.request(file, 'utf-8', null);
  5432. }
  5433. async fetch(file) {
  5434. const stream = await this._context.request(file, null, this._base);
  5435. return new view.Context(this._context, file, stream);
  5436. }
  5437. async require(id) {
  5438. return this._context.require(id);
  5439. }
  5440. error(error, fatal) {
  5441. if (error && this.identifier) {
  5442. error.context = this.identifier;
  5443. }
  5444. this._context.error(error, fatal);
  5445. }
  5446. set(type, value) {
  5447. this.type = type;
  5448. this.value = value;
  5449. return type;
  5450. }
  5451. async peek(type) {
  5452. if (!this._content.has(type)) {
  5453. this._content.set(type, undefined);
  5454. const stream = this.stream;
  5455. if (stream) {
  5456. const position = stream.position;
  5457. const match = (buffer, signature) => {
  5458. return signature.length <= buffer.length && buffer.every((value, index) => signature[index] === undefined || signature[index] === value);
  5459. };
  5460. const buffer = stream.peek(Math.min(stream.length, 16));
  5461. const skip =
  5462. match(buffer, [0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19]) || // PyTorch
  5463. (type !== 'npz' && type !== 'zip' && match(buffer, [0x50, 0x4B, 0x03, 0x04])) || // ZIP
  5464. (type !== 'hdf5' && match(buffer, [0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A])) || // \x89HDF\r\n\x1A\n
  5465. Array.from(this._tags).some(([key, value]) => key !== 'flatbuffers' && key !== 'xml' && value.size > 0) ||
  5466. Array.from(this._content.values()).some((obj) => obj !== undefined);
  5467. if (!skip) {
  5468. switch (type) {
  5469. case 'json': {
  5470. try {
  5471. const buffer = stream.peek(Math.min(stream.length, 0x1000));
  5472. if (stream.length < 0x7ffff000 &&
  5473. (buffer.length < 8 || String.fromCharCode.apply(null, buffer.slice(0, 8)) !== '\x89HDF\r\n\x1A\n') &&
  5474. (buffer.some((v) => v === 0x22 || v === 0x5b || v === 0x5d || v === 0x7b || v === 0x7d))) {
  5475. const json = await import('./json.js');
  5476. const reader = json.TextReader.open(stream);
  5477. if (reader) {
  5478. const obj = reader.read();
  5479. this._content.set(type, obj);
  5480. }
  5481. }
  5482. } catch {
  5483. // continue regardless of error
  5484. }
  5485. break;
  5486. }
  5487. case 'json.gz': {
  5488. try {
  5489. const entries = await this.peek('gzip');
  5490. if (entries && entries.size === 1) {
  5491. const stream = entries.values().next().value;
  5492. const json = await import('./json.js');
  5493. const reader = json.TextReader.open(stream);
  5494. if (reader) {
  5495. const obj = reader.read();
  5496. this._content.set(type, obj);
  5497. }
  5498. }
  5499. } catch {
  5500. // continue regardless of error
  5501. }
  5502. break;
  5503. }
  5504. case 'xml': {
  5505. try {
  5506. const buffer = stream.peek(Math.min(this.stream.length, 0x1000));
  5507. const content = String.fromCharCode.apply(null, buffer);
  5508. if (stream.length < 0x7ffff000 && content.indexOf('<') !== -1 && content.indexOf('</') !== -1) {
  5509. const xml = await import('./xml.js');
  5510. const reader = xml.TextReader.open(this._stream);
  5511. if (reader) {
  5512. const obj = reader.read();
  5513. this._content.set(type, obj);
  5514. }
  5515. }
  5516. } catch {
  5517. // continue regardless of error
  5518. }
  5519. break;
  5520. }
  5521. case 'pkl': {
  5522. let unpickler = null;
  5523. const types = new Set();
  5524. try {
  5525. const zip = await import('./zip.js');
  5526. const archive = zip.Archive.open(stream, 'zlib');
  5527. const data = archive ? archive.entries.get('') : stream;
  5528. let condition = false;
  5529. if (data.length > 4) {
  5530. const head = data.peek(4);
  5531. condition = head[0] === 0x80 && head[1] < 7;
  5532. if (!condition) {
  5533. data.seek(-1);
  5534. const tail = data.peek(1);
  5535. data.seek(0);
  5536. if (tail[0] === 0x2e) {
  5537. const size = Math.min(data.length, 256);
  5538. const buffer = data.peek(size);
  5539. condition =
  5540. (buffer[0] === 0x28 && buffer[1] === 0x64 && buffer[2] === 0x70) ||
  5541. (buffer[0] === 0x28 && buffer[1] === 0x63 && buffer.indexOf(0x0a) !== -1);
  5542. if (!condition) {
  5543. const content = String.fromCharCode.apply(null, buffer);
  5544. const list = ['ccopy_reg', 'cnumpy.core.multiarray', '(dp0'];
  5545. condition = list.some((value) => content.indexOf(value) !== -1);
  5546. }
  5547. }
  5548. }
  5549. }
  5550. if (condition) {
  5551. const python = await import('./python.js');
  5552. const execution = new python.Execution();
  5553. execution.on('resolve', (sender, name) => types.add(name));
  5554. const pickle = execution.__import__('pickle');
  5555. unpickler = new pickle.Unpickler(data);
  5556. }
  5557. } catch {
  5558. // continue regardless of error
  5559. }
  5560. if (unpickler) {
  5561. const storages = new Map();
  5562. unpickler.persistent_load = (saved_id) => {
  5563. if (Array.isArray(saved_id) && saved_id.length > 3) {
  5564. switch (saved_id[0]) {
  5565. case 'storage': {
  5566. const [, storage_type, key, , size] = saved_id;
  5567. if (!storages.has(key)) {
  5568. const storage = new storage_type(size);
  5569. storages.set(key, storage);
  5570. }
  5571. return storages.get(key);
  5572. }
  5573. default: {
  5574. throw new view.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  5575. }
  5576. }
  5577. }
  5578. throw new view.Error("Unsupported 'persistent_load'.");
  5579. };
  5580. try {
  5581. const obj = unpickler.load();
  5582. this._content.set(type, obj);
  5583. } catch (error) {
  5584. this._content.set(type, error);
  5585. }
  5586. if (Array.from(types).every((name) => !name.startsWith('__torch__.'))) {
  5587. for (const name of types) {
  5588. this.error(new view.Error(`Unknown type name '${name}'.`));
  5589. }
  5590. }
  5591. }
  5592. break;
  5593. }
  5594. case 'hdf5': {
  5595. const hdf5 = await import('./hdf5.js');
  5596. const file = hdf5.File.open(stream);
  5597. if (file) {
  5598. try {
  5599. this._content.set(type, file.read());
  5600. } catch (error) {
  5601. this._content.set(type, error);
  5602. }
  5603. }
  5604. break;
  5605. }
  5606. case 'zip':
  5607. case 'tar':
  5608. case 'gzip': {
  5609. this._content.set('zip', undefined);
  5610. this._content.set('tar', undefined);
  5611. this._content.set('gzip', undefined);
  5612. let stream = this._stream;
  5613. try {
  5614. const zip = await import('./zip.js');
  5615. const archive = zip.Archive.open(this._stream, 'gzip');
  5616. if (archive) {
  5617. let entries = archive.entries;
  5618. if (entries.size === 1) {
  5619. const key = entries.keys().next().value;
  5620. stream = entries.values().next().value;
  5621. const name = key === '' ? this.identifier.replace(/\.gz$/, '') : key;
  5622. entries = new Map([[name, stream]]);
  5623. }
  5624. this._content.set('gzip', entries);
  5625. }
  5626. } catch (error) {
  5627. this._content.set('gzip', error);
  5628. }
  5629. let skipTar = false;
  5630. try {
  5631. const zip = await import('./zip.js');
  5632. const archive = zip.Archive.open(stream, 'zip');
  5633. if (archive) {
  5634. this._content.set('zip', archive.entries);
  5635. skipTar = true;
  5636. }
  5637. } catch (error) {
  5638. this._content.set('zip', error);
  5639. }
  5640. if (!skipTar) {
  5641. try {
  5642. const tar = await import('./tar.js');
  5643. const archive = tar.Archive.open(stream);
  5644. if (archive) {
  5645. this._content.set('tar', archive.entries);
  5646. }
  5647. } catch (error) {
  5648. this._content.set('tar', error);
  5649. }
  5650. }
  5651. break;
  5652. }
  5653. case 'flatbuffers.binary': {
  5654. try {
  5655. const flatbuffers = await import('./flatbuffers.js');
  5656. const reader = flatbuffers.BinaryReader.open(this._stream);
  5657. if (reader) {
  5658. this._content.set('flatbuffers.binary', reader);
  5659. }
  5660. } catch (error) {
  5661. this._content.set('flatbuffers.binary', error);
  5662. }
  5663. break;
  5664. }
  5665. case 'npz': {
  5666. const content = new Map();
  5667. const entries = await this.peek('zip');
  5668. if (entries instanceof Map && entries.size > 0 &&
  5669. Array.from(entries.keys()).every((name) => name.endsWith('.npy'))) {
  5670. const python = await import('./python.js');
  5671. const execution = new python.Execution();
  5672. const io = execution.__import__('io');
  5673. const numpy = execution.__import__('numpy');
  5674. for (const [name, stream] of entries) {
  5675. const bytes = new io.BytesIO(stream);
  5676. const array = numpy.load(bytes);
  5677. content.set(name, array);
  5678. }
  5679. this._content.set(type, content);
  5680. }
  5681. break;
  5682. }
  5683. default: {
  5684. throw new view.Error(`Unsupported open format type '${type}'.`);
  5685. }
  5686. }
  5687. }
  5688. if (stream.position !== position) {
  5689. stream.seek(0);
  5690. }
  5691. }
  5692. }
  5693. return this._content.get(type);
  5694. }
  5695. async read(type, ...args) {
  5696. if (!this._content.has(type)) {
  5697. switch (type) {
  5698. case 'json': {
  5699. const json = await import('./json.js');
  5700. const reader = json.TextReader.open(this._stream);
  5701. if (reader) {
  5702. const obj = reader.read();
  5703. this._content.set('json', obj);
  5704. return obj;
  5705. }
  5706. throw new view.Error('Invalid JSON content.');
  5707. }
  5708. case 'bson': {
  5709. const json = await import('./json.js');
  5710. const reader = json.BinaryReader.open(this._stream);
  5711. if (reader) {
  5712. return reader.read();
  5713. }
  5714. throw new view.Error('Invalid BSON content.');
  5715. }
  5716. case 'xml': {
  5717. const xml = await import('./xml.js');
  5718. const reader = xml.TextReader.open(this._stream);
  5719. if (reader) {
  5720. return reader.read();
  5721. }
  5722. throw new view.Error(`Invalid XML content.`);
  5723. }
  5724. case 'flatbuffers.binary': {
  5725. const flatbuffers = await import('./flatbuffers.js');
  5726. const reader = flatbuffers.BinaryReader.open(this._stream);
  5727. if (reader) {
  5728. this._content.set('flatbuffers.reader', reader);
  5729. return reader;
  5730. }
  5731. throw new view.Error('Invalid FlatBuffers content.');
  5732. }
  5733. case 'flatbuffers.text': {
  5734. const flatbuffers = await import('./flatbuffers.js');
  5735. const obj = await this.peek('json');
  5736. return flatbuffers.TextReader.open(obj);
  5737. }
  5738. case 'protobuf.binary': {
  5739. const protobuf = await import('./protobuf.js');
  5740. return protobuf.BinaryReader.open(this._stream);
  5741. }
  5742. case 'protobuf.text': {
  5743. const protobuf = await import('./protobuf.js');
  5744. return protobuf.TextReader.open(this._stream);
  5745. }
  5746. case 'binary.big-endian': {
  5747. return base.BinaryReader.open(this._stream, false);
  5748. }
  5749. case 'binary': {
  5750. return base.BinaryReader.open(this._stream);
  5751. }
  5752. case 'text': {
  5753. const text = await import('./text.js');
  5754. if (typeof args[0] === 'number') {
  5755. const length = Math.min(this._stream.length, args[0]);
  5756. const buffer = this._stream.peek(length);
  5757. return text.Reader.open(buffer);
  5758. }
  5759. return text.Reader.open(this._stream);
  5760. }
  5761. case 'text.decoder': {
  5762. const text = await import('./text.js');
  5763. return text.Decoder.open(this._stream);
  5764. }
  5765. default: {
  5766. break;
  5767. }
  5768. }
  5769. }
  5770. return this.peek(type);
  5771. }
  5772. async tags(type) {
  5773. if (!this._tags.has(type)) {
  5774. let tags = new Map();
  5775. const stream = this.stream;
  5776. if (stream) {
  5777. const position = stream.position;
  5778. const signatures = [
  5779. [0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A], // HDF5
  5780. [0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19], // PyTorch
  5781. [0x50, 0x4b], // ZIP
  5782. [0x1f, 0x8b] // gzip
  5783. ];
  5784. let skip = false;
  5785. if (signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value))) {
  5786. skip = true;
  5787. } else if (Array.from(this._tags).some(([key, value]) => key !== 'flatbuffers' && value.size > 0) && type !== 'pb+') {
  5788. skip = true;
  5789. } else if (Array.from(this._content.values()).some((obj) => obj !== undefined)) {
  5790. skip = true;
  5791. } else if (stream.length < 0x7ffff000) {
  5792. const json = await import('./json.js');
  5793. if (json.TextReader.open(stream)) {
  5794. skip = true;
  5795. }
  5796. }
  5797. if (!skip && stream.length < 0x7ffff000) {
  5798. try {
  5799. switch (type) {
  5800. case 'pbtxt': {
  5801. const protobuf = await import('./protobuf.js');
  5802. const reader = protobuf.TextReader.open(stream);
  5803. tags = reader ? reader.signature() : tags;
  5804. break;
  5805. }
  5806. case 'pb': {
  5807. const protobuf = await import('./protobuf.js');
  5808. const reader = protobuf.BinaryReader.open(stream);
  5809. tags = reader.signature();
  5810. break;
  5811. }
  5812. case 'pb+': {
  5813. const protobuf = await import('./protobuf.js');
  5814. const reader = protobuf.BinaryReader.open(stream);
  5815. tags = reader.decode();
  5816. break;
  5817. }
  5818. case 'xml': {
  5819. const xml = await import('./xml.js');
  5820. const reader = xml.TextReader.open(stream);
  5821. if (reader) {
  5822. const document = reader.read(1);
  5823. const element = document.documentElement;
  5824. const namespaceURI = element.namespaceURI;
  5825. const localName = element.localName;
  5826. const name = namespaceURI ? `${namespaceURI}:${localName}` : localName;
  5827. tags.set(name, element);
  5828. }
  5829. break;
  5830. }
  5831. default: {
  5832. throw new view.Error(`Unsupported tags format type '${type}'.`);
  5833. }
  5834. }
  5835. } catch {
  5836. tags.clear();
  5837. }
  5838. }
  5839. if (stream.position !== position) {
  5840. stream.seek(position);
  5841. }
  5842. }
  5843. this._tags.set(type, tags);
  5844. }
  5845. return this._tags.get(type);
  5846. }
  5847. async metadata(name) {
  5848. return view.Metadata.open(this, name);
  5849. }
  5850. };
  5851. view.EntryContext = class {
  5852. constructor(host, entries) {
  5853. this._host = host;
  5854. this._entries = entries;
  5855. }
  5856. async request(file, encoding, base) {
  5857. if (base === null) {
  5858. return this._host.request(file, encoding, base);
  5859. }
  5860. let stream = null;
  5861. if (typeof base === 'string') {
  5862. stream = this._entries.get(`${base}/${file}`) || this._entries.get(`${base}\\${file}`);
  5863. } else {
  5864. stream = this._entries.get(file);
  5865. }
  5866. if (!stream) {
  5867. throw new view.Error('File not found.');
  5868. }
  5869. if (encoding) {
  5870. const decoder = new TextDecoder(encoding);
  5871. const buffer = stream.peek();
  5872. return decoder.decode(buffer);
  5873. }
  5874. return stream;
  5875. }
  5876. async require(id) {
  5877. return this._host.require(id);
  5878. }
  5879. get entries() {
  5880. return this._entries;
  5881. }
  5882. error(error, fatal) {
  5883. this._host.exception(error, fatal);
  5884. }
  5885. };
  5886. view.ArchiveError = class extends Error {
  5887. constructor(message) {
  5888. super(message);
  5889. this.name = 'Error loading archive.';
  5890. }
  5891. };
  5892. view.ModelFactoryService = class {
  5893. constructor(host) {
  5894. this._host = host;
  5895. this._patterns = new Set(['.zip', '.tar', '.tar.gz', '.tgz', '.gz']);
  5896. this._factories = [];
  5897. /* eslint-disable no-control-regex */
  5898. this.register('./message', ['.message', '.netron', '.maxviz']);
  5899. this.register('./pytorch', ['.pt', '.pth', '.ptl', '.pt1', '.pt2', '.pyt', '.pyth', '.pkl', '.pickle', '.h5', '.t7', '.model', '.dms', '.tar', '.ckpt', '.chkpt', '.tckpt', '.bin', '.pb', '.zip', '.nn', '.torchmodel', '.torchscript', '.pytorch', '.ot', '.params', '.trt', '.ff', '.ptmf', '.jit', '.bin.index.json', 'model.json', '.ir', 'serialized_exported_program.json', 'serialized_state_dict.json', 'archive_format'], ['.model', '.pt2'], [/^\x80.\x8a\x0a\x6c\xfc\x9c\x46\xf9\x20\x6a\xa8\x50\x19/]);
  5900. this.register('./onnx', ['.onnx', '.onnx.data', '.onnx.meta', '.onn', '.pb', '.onnxtxt', '.pbtxt', '.prototxt', '.txt', '.model', '.pt', '.pth', '.pkl', '.ort', '.ort.onnx', '.ngf', '.json', '.bin', 'onnxmodel'], [], [/^\x08[\x00-\x10]\x12[\x00-\x20]\w\w/, /^\x08[\x00-\x10]\x12\x00\x1A/, /^\x08[\x00-\x10]\x3A/, /^\s*ir_version:\s\d+/, /^....ORTM/]);
  5901. this.register('./tflite', ['.tflite', '.lite', '.tfl', '.bin', '.pb', '.tmfile', '.h5', '.model', '.json', '.txt', '.dat', '.nb', '.ckpt', '.onnx'], [], [/^....TFL3/]);
  5902. this.register('./mxnet', ['.json', '.params'], ['.mar']);
  5903. this.register('./coreml', ['.mlmodel', '.bin', 'manifest.json', 'metadata.json', 'featuredescriptions.json', '.pb', '.pbtxt', '.mil'], ['.mlpackage', '.mlmodelc']);
  5904. this.register('./caffe', ['.caffemodel', '.pbtxt', '.prototxt', '.pt', '.txt']);
  5905. this.register('./caffe2', ['.pb', '.pbtxt', '.prototxt']);
  5906. this.register('./torch', ['.t7', '.net']);
  5907. this.register('./tf', ['.pb', '.meta', '.pbtxt', '.prototxt', '.txt', '.pt', '.json', '.index', '.ckpt', '.graphdef', '.pbmm', /.data-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]$/, /^events.out.tfevents./, /^.*group\d+-shard\d+of\d+(\.bin)?$/], ['.zip']);
  5908. this.register('./tensorrt', ['.trt', '.trtmodel', '.engine', '.model', '.txt', '.uff', '.pb', '.tmfile', '.onnx', '.pth', '.dnn', '.plan', '.pt', '.dat', '.bin'], [], [/^ptrt/, /^ftrt/]);
  5909. this.register('./keras', ['.h5', '.hd5', '.hdf5', '.keras', '.json', '.cfg', '.model', '.pb', '.pth', '.weights', '.pkl', '.lite', '.tflite', '.ckpt', '.pb', 'model.weights.npz', /^.*group\d+-shard\d+of\d+(\.bin)?$/], ['.zip'], [/^\x89HDF\r\n\x1A\n/]);
  5910. this.register('./safetensors', ['.safetensors', '.safetensors.index.json']);
  5911. this.register('./numpy', ['.npz', '.npy', '.pkl', '.pickle', '.model', '.model2', '.mge', '.joblib', '']);
  5912. this.register('./lasagne', ['.pkl', '.pickle', '.joblib', '.model', '.pkl.z', '.joblib.z']);
  5913. this.register('./lightgbm', ['.txt', '.pkl', '.model']);
  5914. this.register('./sklearn', ['.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pickle.dat', '.bin']);
  5915. this.register('./megengine', ['.tm', '.mge', '.pkl']);
  5916. this.register('./pickle', ['.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pdstates', '.mge', '.bin', '.npy', '.pth']);
  5917. this.register('./cntk', ['.model', '.cntk', '.cmf', '.dnn']);
  5918. this.register('./uff', ['.uff', '.pb', '.pbtxt', '.uff.txt', '.trt', '.engine']);
  5919. this.register('./paddle', ['.pdmodel', '.pdiparams', '.pdparams', '.pdopt', '.paddle', '__model__', '.__model__', '.pbtxt', '.txt', '.tar', '.tar.gz', '.nb', '.json']);
  5920. this.register('./bigdl', ['.model', '.bigdl']);
  5921. this.register('./darknet', ['.cfg', '.model', '.txt', '.weights']);
  5922. this.register('./mediapipe', ['.pbtxt']);
  5923. this.register('./executorch', ['.pte'], [], [/^....ET12/]);
  5924. this.register('./rknn', ['.rknn', '.nb', '.onnx', '.json', '.bin', /^model$/], [], [/^RKNN/, /^VPMN/], /^....RKNN/);
  5925. this.register('./dlc', ['.dlc', /^model$/, '.params']);
  5926. this.register('./armnn', ['.armnn', '.json']);
  5927. this.register('./mnn', ['.mnn']);
  5928. this.register('./ncnn', ['.param', '.bin', '.cfg.ncnn', '.weights.ncnn', '.ncnnmodel']);
  5929. this.register('./tnn', ['.tnnproto', '.tnnmodel']);
  5930. this.register('./tengine', ['.tmfile']);
  5931. this.register('./mslite', ['.ms', '.bin'], [], [/^....MSL0/, /^....MSL1/, /^....MSL2/]);
  5932. this.register('./barracuda', ['.nn']);
  5933. this.register('./circle', ['.circle'], [], [/^....CIR0/]);
  5934. this.register('./dnn', ['.dnn']);
  5935. this.register('./xmodel', ['.xmodel']);
  5936. this.register('./kmodel', ['.kmodel']);
  5937. this.register('./flux', ['.bson']);
  5938. this.register('./dl4j', ['.json', '.bin']);
  5939. this.register('./openvino', ['.xml', '.bin']);
  5940. this.register('./mlnet', ['.zip', '.mlnet']);
  5941. this.register('./acuity', ['.json']);
  5942. this.register('./imgdnn', ['.dnn', 'params', '.json']);
  5943. this.register('./flax', ['.msgpack']);
  5944. this.register('./om', ['.om', '.onnx', '.pb', '.engine', '.bin'], [], [/^IMOD/, /^PICO/]);
  5945. this.register('./gguf', ['.gguf', /^[^.]+$/], [], [/^GGUF/]);
  5946. this.register('./nnabla', ['.nntxt'], ['.nnp']);
  5947. this.register('./hickle', ['.h5', '.hkl']);
  5948. this.register('./nnef', ['.nnef', '.dat']);
  5949. this.register('./onednn', ['.json']);
  5950. this.register('./espresso', ['.espresso.net', '.espresso.shape', '.espresso.weights'], ['.mlmodelc']);
  5951. this.register('./mlir', ['.mlir', '.mlir.txt', '.mlirbc', '.txt']);
  5952. this.register('./sentencepiece', ['.model']);
  5953. this.register('./hailo', ['.hn', '.har', '.metadata.json']);
  5954. this.register('./tvm', ['.json', '.params']);
  5955. this.register('./dot', ['.dot'], [], [/^\s*(\/\*[\s\S]*?\*\/|\/\/.*|#.*)?\s*digraph\s*([A-Za-z][A-Za-z0-9-_]*|".*?")?\s*{/m]);
  5956. this.register('./catboost', ['.cbm']);
  5957. this.register('./weka', ['.model']);
  5958. this.register('./qnn', ['.json', '.bin', '.serialized', '.dlc']);
  5959. this.register('./kann', ['.kann', '.bin', '.kgraph'], [], [/^....KaNN/]);
  5960. this.register('./xgboost', ['.xgb', '.xgboost', '.json', '.model', '.bin', '.txt'], [], [/^{L\x00\x00/, /^binf/, /^bs64/, /^\s*booster\[0\]:/]);
  5961. this.register('./transformers', ['.json']);
  5962. this.register('', ['.cambricon', '.vnnmodel', '.nnc']);
  5963. /* eslint-enable no-control-regex */
  5964. }
  5965. register(module, extensions, containers, contents) {
  5966. for (const extension of extensions) {
  5967. this._factories.push({ extension, module });
  5968. this._patterns.add(extension);
  5969. }
  5970. for (const content of contents || []) {
  5971. this._factories.push({ content, module });
  5972. }
  5973. for (const container of containers || []) {
  5974. this._patterns.add(container);
  5975. }
  5976. }
  5977. async open(context) {
  5978. try {
  5979. await this._openSignature(context);
  5980. const content = new view.Context(context);
  5981. const model = await this._openContext(content);
  5982. if (!model) {
  5983. const check = (obj) => {
  5984. if (obj instanceof Error) {
  5985. throw obj;
  5986. }
  5987. return obj instanceof Map && obj.size > 0;
  5988. };
  5989. let entries = context.entries;
  5990. if (!check(entries)) {
  5991. entries = await content.peek('zip');
  5992. if (!check(entries)) {
  5993. entries = await content.peek('tar');
  5994. if (!check(entries)) {
  5995. entries = await content.peek('gzip');
  5996. }
  5997. }
  5998. }
  5999. if (!check(entries)) {
  6000. await this._unsupported(content);
  6001. }
  6002. const entryContext = await this._openEntries(entries);
  6003. if (!entryContext) {
  6004. await this._unsupported(content);
  6005. }
  6006. return this._openContext(entryContext);
  6007. }
  6008. return model;
  6009. } catch (error) {
  6010. if (!error.context && context) {
  6011. error.context = context.identifier || '';
  6012. const stream = context.stream;
  6013. if (stream) {
  6014. try {
  6015. const hex = (buffer) => Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  6016. const position = stream.position;
  6017. stream.seek(0);
  6018. const head = stream.peek(Math.min(16, stream.length));
  6019. error.context += `|${hex(head)}`;
  6020. if (stream.length > 16) {
  6021. stream.seek(stream.length - 16);
  6022. const tail = stream.peek(16);
  6023. error.context += `|${hex(tail)}`;
  6024. }
  6025. stream.seek(position);
  6026. } catch {
  6027. // continue regardless of error
  6028. }
  6029. }
  6030. }
  6031. throw error;
  6032. }
  6033. }
  6034. async _unsupported(context) {
  6035. const identifier = context.identifier;
  6036. const stream = context.stream;
  6037. const zip = await import('./zip.js');
  6038. const tar = await import('./tar.js');
  6039. const callbacks = [
  6040. (stream) => zip.Archive.open(stream, 'zip'),
  6041. (stream) => tar.Archive.open(stream),
  6042. (stream) => zip.Archive.open(stream, 'gzip')
  6043. ];
  6044. for (const callback of callbacks) {
  6045. let archive = null;
  6046. try {
  6047. archive = callback(stream);
  6048. } catch {
  6049. // continue regardless of error
  6050. }
  6051. if (archive) {
  6052. throw new view.Error("Archive contains no model files.");
  6053. }
  6054. }
  6055. const regex = async() => {
  6056. const entries = [
  6057. { name: 'Unity metadata', value: /fileFormatVersion:/ },
  6058. ];
  6059. const buffer = stream.peek(Math.min(4096, stream.length));
  6060. const content = String.fromCharCode.apply(null, buffer);
  6061. for (const entry of entries) {
  6062. if (content.match(entry.value) && (!entry.identifier || context.identifier.match(entry.identifier))) {
  6063. throw new view.Error(`Invalid file content. File contains ${entry.name}.`);
  6064. }
  6065. }
  6066. };
  6067. const json = async () => {
  6068. const obj = await context.peek('json');
  6069. if (obj) {
  6070. const formats = [
  6071. { name: 'Netron metadata', tags: ['[].name', '[].schema'] },
  6072. { name: 'Netron metadata', tags: ['[].name', '[].attributes'] },
  6073. { name: 'Netron metadata', tags: ['[].name', '[].category'] },
  6074. { name: 'Netron test data', tags: ['[].type', '[].target', '[].source', '[].format', '[].link'] },
  6075. { name: 'Netron configuration', tags: ['recents', 'consent'] },
  6076. { name: 'Netron metrics data', tags: ['signature', 'metrics'] },
  6077. { name: 'Darkflow metadata', tags: ['net', 'type', 'model'] },
  6078. { name: 'keras-yolo2 configuration', tags: ['model', 'train', 'valid'] },
  6079. { name: 'Vulkan SwiftShader ICD manifest', tags: ['file_format_version', 'ICD'] },
  6080. { name: 'DeepLearningExamples configuration', tags: ['attention_probs_dropout_prob', 'hidden_act', 'hidden_dropout_prob', 'hidden_size',] },
  6081. { name: 'GitHub page data', tags: ['payload', 'title'] },
  6082. { name: 'NuGet assets', tags: ['version', 'targets', 'packageFolders'] },
  6083. { name: 'NuGet data', tags: ['format', 'restore', 'projects'] },
  6084. { name: 'NPM package', tags: ['name', 'version', 'dependencies'] },
  6085. { name: 'NPM package lock data', tags: ['name', 'version', 'lockfileVersion'] },
  6086. { name: 'NetworkX adjacency_data', tags: ['directed', 'graph', 'nodes'] },
  6087. { name: 'Waifu2x data', tags: ['name', 'arch_name', 'channels'] },
  6088. { name: 'Waifu2x data', tags: ['[].nInputPlane', '[].nOutputPlane', '[].weight', '[].bias'] },
  6089. { name: 'Brain.js data', tags: ['type', 'sizes', 'layers'] },
  6090. { name: 'Custom Vision metadata', tags: ['CustomVision.Metadata.Version'] },
  6091. { name: 'W&B metadata', tags: ['program', 'host', 'executable'] },
  6092. { name: 'TypeScript configuration data', tags: ['compilerOptions'] },
  6093. { name: 'CatBoost model', tags: ['features_info', 'model_info'] },
  6094. { name: 'TPU-MLIR tensor location data', tags: ['file-line', 'subnet_id', 'core_id'] }, // https://github.com/sophgo/tpu-mlir/blob/master/lib/Dialect/Tpu/Transforms/Codegen/TensorLocation.cpp
  6095. { name: 'HTTP Archive data', tags: ['log.version', 'log.creator', 'log.entries'] }, // https://w3c.github.io/web-performance/specs/HAR/Overview.html
  6096. { name: 'Trace Event data', tags: ['traceEvents'] },
  6097. { name: 'Trace Event data', tags: ['[].pid', '[].ph'] },
  6098. { name: 'Diffusers configuration', tags: ['_class_name', '_diffusers_version'] },
  6099. { name: 'Tokenizer data', tags: ['<eos>', '<bos>'] },
  6100. { name: 'Jupyter Notebook data', tags: ['cells', 'nbformat'] },
  6101. { name: 'Kaggle credentials', tags: ['username','key'] },
  6102. { name: '.NET runtime configuration', tags: ['runtimeOptions.configProperties'] },
  6103. { name: '.NET dependency manifest', tags: ['runtimeTarget', 'targets', 'libraries'] },
  6104. { name: 'GuitarML NeuralPi model data', tags: ['model_data', 'state_dict'] },
  6105. { name: 'GuitarML SmartAmpPro model data', tags: ['conv1d', 'conv1d_stride'] },
  6106. { name: 'GuitarML SmartAmp model data', tags: ['activation', 'output_channels', 'input_channels', 'residual_channels'] },
  6107. { name: 'Keras configuration data', tags: ['floatx', 'epsilon', 'backend'] },
  6108. { name: 'PIMCOMP-NN model data', tags: ['node_list', 'reshape_info'] },
  6109. { name: 'AIMET encodings', tags: ['activation_encodings'] },
  6110. ];
  6111. const match = (obj, tag) => {
  6112. if (tag.startsWith('[].')) {
  6113. tag = tag.substring(3);
  6114. return (Array.isArray(obj) && obj.some((item) => Object.prototype.hasOwnProperty.call(item, tag)));
  6115. }
  6116. tag = tag.split('.');
  6117. while (tag.length > 1) {
  6118. const key = tag.shift();
  6119. obj = obj[key];
  6120. if (!obj) {
  6121. return false;
  6122. }
  6123. }
  6124. return Object.prototype.hasOwnProperty.call(obj, tag[0]);
  6125. };
  6126. for (const format of formats) {
  6127. if (format.tags.every((tag) => match(obj, tag))) {
  6128. throw new view.Error(`Invalid file content. File contains ${format.name}.`);
  6129. }
  6130. }
  6131. const content = `${JSON.stringify(obj).substring(0, 100).replace(/\s/, '').substring(0, 48)}...`;
  6132. throw new view.Error(`Unsupported JSON content '${content.length > 64 ? `${content.substring(0, 100)}...` : content}'.`);
  6133. }
  6134. };
  6135. const pbtxt = async () => {
  6136. const formats = [
  6137. { name: 'ImageNet LabelMap data', tags: ['entry', 'entry.target_class'] },
  6138. { name: 'StringIntLabelMapProto data', tags: ['item', 'item.id', 'item.name'] },
  6139. { name: 'caffe.LabelMap data', tags: ['item', 'item.name', 'item.label'] },
  6140. { name: 'Triton Inference Server configuration', tags: ['input', 'output', 'name', 'platform'] }, // https://github.com/triton-inference-server/common/blob/main/protobuf/model_config.proto
  6141. { name: 'Triton Inference Server configuration', tags: ['input', 'output', 'backend'] },
  6142. { name: 'Triton Inference Server configuration', tags: ['input', 'output', 'max_batch_size'] },
  6143. { name: 'Triton Inference Server configuration', tags: ['input', 'output', 'instance_group'] },
  6144. { name: 'Triton Inference Server configuration', tags: ['default_model_filename', 'max_batch_size'] },
  6145. { name: 'TensorFlow OpList data', tags: ['op', 'op.name', 'op.input_arg'] },
  6146. { name: 'vitis.ai.proto.DpuModelParamList data', tags: ['model', 'model.name', 'model.kernel'] },
  6147. { name: 'object_detection.protos.DetectionModel data', tags: ['model', 'model.ssd'] },
  6148. { name: 'object_detection.protos.DetectionModel data', tags: ['model', 'model.faster_rcnn'] },
  6149. { name: 'tensorflow.CheckpointState data', tags: ['model_checkpoint_path', 'all_model_checkpoint_paths'] },
  6150. { name: 'apollo.perception.camera.traffic_light.detection.DetectionParam data', tags: ['min_crop_size', 'crop_method'] },
  6151. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['caffe_ssd'] }, // https://github.com/TexasInstruments/edgeai-mmdetection/blob/master/mmdet/utils/proto/mmdet_meta_arch.proto
  6152. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tf_od_api_ssd'] },
  6153. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_ssd'] },
  6154. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_faster_rcnn'] },
  6155. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_yolo'] },
  6156. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_retinanet'] },
  6157. { name: 'domi.InsertNewOps data', tags: ['aipp_op'] } // https://github.com/Ascend/parser/blob/development/parser/proto/insert_op.proto
  6158. ];
  6159. const tags = await context.tags('pbtxt');
  6160. if (tags.size > 0) {
  6161. for (const format of formats) {
  6162. if (format.tags.every((tag) => tags.has(tag))) {
  6163. const error = new view.Error(`Invalid file content. File contains ${format.name}.`);
  6164. error.context = context.identifier;
  6165. throw error;
  6166. }
  6167. }
  6168. const entries = [];
  6169. entries.push(...Array.from(tags).filter(([key]) => key.toString().indexOf('.') === -1));
  6170. entries.push(...Array.from(tags).filter(([key]) => key.toString().indexOf('.') !== -1));
  6171. const content = entries.map(([key, value]) => value === true ? key : `${key}:${JSON.stringify(value)}`).join(',');
  6172. throw new view.Error(`Unsupported Protocol Buffers text content '${content.length > 64 ? `${content.substring(0, 100)}...` : content}'.`);
  6173. }
  6174. };
  6175. const pb = async () => {
  6176. const tags = await context.tags('pb+');
  6177. if (Object.keys(tags).length > 0) {
  6178. const formats = [
  6179. { name: 'sentencepiece.ModelProto data', tags: [[1,[[1,2],[2,5],[3,0]]],[2,[[1,2],[2,2],[3,0],[4,0],[5,2],[6,0],[7,2],[10,5],[16,0],[40,0],[41,0],[42,0],[43,0]]],[3,[]],[4,[]],[5,[]]] }, // https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  6180. { name: 'mediapipe.BoxDetectorIndex data', tags: [[1,[[1,[[1,[[1,5],[2,5],[3,5],[4,5],[6,0],[7,5],[8,5],[10,5],[11,0],[12,0]]],[2,5],[3,[]]]],[2,false],[3,false],[4,false],[5,false]]],[2,false],[3,false]] }, // https://github.com/google-ai-edge/mediapipe/blob/2b5a50fff37f79db8103dbd88f552c1a9be31e51/mediapipe/util/tracking/box_detector.proto
  6181. { name: 'third_party.tensorflow.python.keras.protobuf.SavedMetadata data', tags: [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]] },
  6182. { name: 'pblczero.Net data', tags: [[1,5],[2,2],[3,[[1,0],[2,0],[3,0]],[10,[[1,[]],[2,[]],[3,[]],[4,[]],[5,[]],[6,[]]]],[11,[]]]] }, // https://github.com/LeelaChessZero/lczero-common/blob/master/proto/net.proto
  6183. { name: 'chrome_browser_media.PreloadedData', tags: [[1,2]], identifier: 'preloaded_data.pb' }, // https://github.com/kiwibrowser/src/blob/86afd150b847c9dd6f9ad3faddee1a28b8c9b23b/chrome/browser/media/media_engagement_preload.proto#L9
  6184. { name: 'mind_ir.ModelProto', tags: [[1,2],[2,2],[5,2],[7,[]],[10,0],[12,[]],[13,0]] }, // https://github.com/mindspore-ai/mindspore/blob/master/mindspore/core/proto/mind_ir.proto
  6185. { name: 'mindspore.irpb.Checkpoint', tags: [[1,[[1,2],[2,[[1,0],[2,2],[3,2]]]]]] }, // https://github.com/mindspore-ai/mindspore/blob/master/mindspore/ccsrc/utils/checkpoint.proto
  6186. { name: 'optimization_guide.proto.PageTopicsOverrideList data', tags: [[1,[[1,2],[2,[]]]]] }, // https://github.com/chromium/chromium/blob/main/components/optimization_guide/proto/page_topics_override_list.proto
  6187. { name: 'optimization_guide.proto.ModelInfo data', tags: [[1,0],[2,0],[4,0],[6,false],[7,[]],[9,0]] }, // https://github.com/chromium/chromium/blob/22b0d711657b451b61d50dd2e242b3c6e38e6ef5/components/optimization_guide/proto/models.proto#L80
  6188. { name: 'Horizon binary model', tags: [[1,0],[2,0],[5,[[7,2],[8,2]]],[6,[[1,[[1,2],[2,2]]]]]] }, // https://github.com/HorizonRDK/hobot_dnn
  6189. { name: 'TensorFlow Profiler data', tags: [[1,[[2,2],[3,[]],[4,[]]]]] }, // https://github.com/tensorflow/tensorflow/blob/master/third_party/xla/third_party/tsl/tsl/profiler/protobuf/xplane.proto
  6190. ];
  6191. const match = (tags, schema) => {
  6192. for (const [key, inner] of schema) {
  6193. const value = tags[key];
  6194. if (value === undefined) {
  6195. continue;
  6196. }
  6197. if (inner === false) {
  6198. return false;
  6199. }
  6200. if (Array.isArray(inner)) {
  6201. if (typeof value !== 'object' || !match(value, inner)) {
  6202. return false;
  6203. }
  6204. } else if (inner !== value) {
  6205. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  6206. return true;
  6207. }
  6208. return false;
  6209. }
  6210. }
  6211. return true;
  6212. };
  6213. for (const format of formats) {
  6214. if (match(tags, format.tags) && (!format.identifier || identifier === context.identifier)) {
  6215. const error = new view.Error(`Invalid file content. File contains ${format.name}.`);
  6216. error.context = context.identifier;
  6217. throw error;
  6218. }
  6219. }
  6220. const format = (tags) => {
  6221. const content = Object.entries(tags).map(([key, value]) => {
  6222. return `${key}:${Object(value) === value ? `{${format(value)}}` : value}`;
  6223. });
  6224. return content.join(',');
  6225. };
  6226. const content = format(tags);
  6227. const message = content.length > 64 ? `${content.substring(0, 100)}...` : content;
  6228. throw new view.Error(`Unsupported Protocol Buffers content or ambiguous file extension '${message}'.`);
  6229. }
  6230. };
  6231. const flatbuffers = async () => {
  6232. const stream = context.stream;
  6233. if (stream && stream.length >= 8) {
  6234. let identifier = null;
  6235. const reader = await context.peek('flatbuffers.binary');
  6236. if (reader) {
  6237. identifier = reader.identifier;
  6238. } else {
  6239. const data = stream.peek(8);
  6240. if (data[0] >= 8 && data[0] <= 0x28 && (data[0] & 3) === 0 && data[1] === 0x00 && data[2] === 0x00 && data[3] === 0x00) {
  6241. identifier = String.fromCharCode.apply(null, data.slice(4, 8));
  6242. }
  6243. }
  6244. if (identifier) {
  6245. const formats = [
  6246. { name: 'ONNX Runtime model data', identifier: 'ORTM' },
  6247. { name: 'TensorFlow Lite model data', identifier: 'TFL3' },
  6248. { name: 'ExecuTorch model data', identifier: 'ET12' },
  6249. { name: 'NNC model data', identifier: 'ENNC' },
  6250. { name: 'KaNN model data', identifier: 'KaNN' },
  6251. { name: 'Circle model data', identifier: 'CIR0' },
  6252. { name: 'MindSpore Lite model data', identifier: 'MSL0' },
  6253. { name: 'MindSpore Lite model data', identifier: 'MSL1' },
  6254. { name: 'MindSpore Lite model data', identifier: 'MSL2' },
  6255. { name: 'MindSpore Lite model data', identifier: 'MSL3' },
  6256. { name: 'NVDA model data', identifier: 'NVDA' },
  6257. { name: 'BSTM model data', identifier: 'BSTM' },
  6258. { name: 'onnu model data', identifier: 'onnu' },
  6259. { name: 'ONNX Runtime On-Device Training Checkpoint', identifier: 'ODTC' }
  6260. ];
  6261. for (const format of formats) {
  6262. if (identifier === format.identifier) {
  6263. throw new view.Error(`Invalid file content. File contains ${format.name}.`);
  6264. }
  6265. }
  6266. }
  6267. }
  6268. };
  6269. const xml = async () => {
  6270. const document = await context.peek('xml');
  6271. if (document && document.documentElement) {
  6272. const tags = new Set();
  6273. const qualifiedName = (element) => {
  6274. const namespaceURI = element.namespaceURI;
  6275. const localName = element.localName;
  6276. return namespaceURI ? `${namespaceURI}:${localName}` : localName;
  6277. };
  6278. const root = qualifiedName(document.documentElement);
  6279. tags.add(root);
  6280. for (const element of document.documentElement.childNodes) {
  6281. const name = qualifiedName(element);
  6282. tags.add(`${root}/${name}`);
  6283. }
  6284. const formats = [
  6285. { name: 'OpenCV storage data', tags: ['opencv_storage'] },
  6286. { name: 'XHTML markup', tags: ['http://www.w3.org/1999/xhtml:html'] },
  6287. { name: '.NET XML documentation', tags: ['doc', 'doc/assembly'] },
  6288. { name: '.NET XML documentation', tags: ['doc', 'doc/members'] }
  6289. ];
  6290. for (const format of formats) {
  6291. if (format.tags.every((tag) => tags.has(tag))) {
  6292. const error = new view.Error(`Invalid file content. File contains ${format.name}.`);
  6293. error.content = context.identifier;
  6294. throw error;
  6295. }
  6296. }
  6297. throw new view.Error(`Unsupported XML content '${tags.keys().next().value}'.`);
  6298. }
  6299. };
  6300. const hdf5 = async () => {
  6301. const obj = await context.peek('hdf5');
  6302. if (obj instanceof Error) {
  6303. throw obj;
  6304. }
  6305. if (obj) {
  6306. throw new view.Error(`Invalid file content. File contains HDF5 content.`);
  6307. }
  6308. };
  6309. const unknown = async () => {
  6310. if (stream) {
  6311. throw new view.Error(`Unsupported file content.`);
  6312. }
  6313. throw new view.Error("Unsupported file directory.");
  6314. };
  6315. await regex();
  6316. await json();
  6317. await pbtxt();
  6318. await pb();
  6319. await flatbuffers();
  6320. await xml();
  6321. await hdf5();
  6322. await unknown();
  6323. }
  6324. async _require(id) {
  6325. const module = await this._host.require(id);
  6326. if (!module || !module.ModelFactory) {
  6327. throw new view.Error(`Failed to load module '${id}'.`);
  6328. }
  6329. return new module.ModelFactory();
  6330. }
  6331. async _openContext(context) {
  6332. const modules = this._filter(context).filter((module) => module && module.length > 0);
  6333. const errors = [];
  6334. for (const module of modules) {
  6335. /* eslint-disable no-await-in-loop */
  6336. const factory = await this._require(module);
  6337. const type = await factory.match(context);
  6338. /* eslint-enable no-await-in-loop */
  6339. if (context.stream && context.stream.position !== 0) {
  6340. throw new view.Error('Invalid stream position.');
  6341. }
  6342. if (type) {
  6343. try {
  6344. /* eslint-disable no-await-in-loop */
  6345. const model = await factory.open(context);
  6346. /* eslint-enable no-await-in-loop */
  6347. if (!model.identifier) {
  6348. model.identifier = context.identifier;
  6349. }
  6350. model.attachment = new metadata.Attachment();
  6351. return model;
  6352. } catch (error) {
  6353. delete context.type;
  6354. delete context.value;
  6355. const stream = context.stream;
  6356. if (stream && stream.position !== 0) {
  6357. stream.seek(0);
  6358. }
  6359. errors.push(error);
  6360. }
  6361. }
  6362. if (context.stream && context.stream.position !== 0) {
  6363. throw new view.Error('Invalid stream position.');
  6364. }
  6365. }
  6366. if (errors.length > 0) {
  6367. if (errors.length === 1) {
  6368. throw errors[0];
  6369. }
  6370. throw new view.Error(errors.map((err) => err.message).join('\n'));
  6371. }
  6372. return null;
  6373. }
  6374. async _openEntries(entries) {
  6375. try {
  6376. const rootFolder = (files) => {
  6377. const map = files.map((file) => file.split('/').slice(0, -1));
  6378. const at = (index) => (list) => list[index];
  6379. const rotate = (list) => list.length === 0 ? [] : list[0].map((item, index) => list.map(at(index)));
  6380. const equals = (list) => list.every((item) => item === list[0]);
  6381. const folder = rotate(map).filter(equals).map(at(0)).join('/');
  6382. return folder.length === 0 ? folder : `${folder}/`;
  6383. };
  6384. const files = Array.from(entries).filter(([name]) => !(name.endsWith('/') || name.split('/').pop().startsWith('.') || (!name.startsWith('./') && name.startsWith('.'))));
  6385. const folder = rootFolder(files.map(([name]) => name));
  6386. const filter = async (queue, entries) => {
  6387. entries = new Map(Array.from(entries)
  6388. .filter(([path]) => path.startsWith(folder))
  6389. .map(([path, stream]) => [path.substring(folder.length), stream]));
  6390. const entryContext = new view.EntryContext(this._host, entries);
  6391. let matches = [];
  6392. for (const [name, stream] of queue) {
  6393. const identifier = name.substring(folder.length);
  6394. const context = new view.Context(entryContext, identifier, stream);
  6395. const modules = this._filter(context);
  6396. for (const module of modules) {
  6397. /* eslint-disable no-await-in-loop */
  6398. const factory = await this._require(module);
  6399. const type = await factory.match(context);
  6400. /* eslint-enable no-await-in-loop */
  6401. if (context.stream && context.stream.position !== 0) {
  6402. throw new view.Error('Invalid stream position.');
  6403. }
  6404. delete context.value;
  6405. if (type) {
  6406. matches = matches.filter((match) => !factory.filter || factory.filter(context, match));
  6407. if (matches.every((match) => !match.factory.filter || match.factory.filter(match, context))) {
  6408. context.factory = factory;
  6409. matches.push(context);
  6410. }
  6411. break;
  6412. }
  6413. }
  6414. }
  6415. if (matches.length > 1) {
  6416. const content = matches.map((context) => context.type).join(',');
  6417. throw new view.ArchiveError(`Archive contains multiple model files '${content}'.`);
  6418. }
  6419. if (matches.length > 0) {
  6420. const match = matches.shift();
  6421. delete match.type;
  6422. delete match.factory;
  6423. return match;
  6424. }
  6425. return null;
  6426. };
  6427. const queue = files.filter(([name]) => name.substring(folder.length).indexOf('/') < 0);
  6428. let context = await filter(queue, entries);
  6429. if (!context) {
  6430. const queue = files.filter(([name]) => name.substring(folder.length).indexOf('/') >= 0);
  6431. context = await filter(queue, entries);
  6432. }
  6433. return context;
  6434. } catch (error) {
  6435. throw new view.ArchiveError(error.message);
  6436. }
  6437. }
  6438. accept(identifier, size) {
  6439. const extension = identifier.indexOf('.') === -1 ? '' : identifier.split('.').pop().toLowerCase();
  6440. identifier = identifier.toLowerCase().split('/').pop();
  6441. let accept = false;
  6442. for (const extension of this._patterns) {
  6443. if ((typeof extension === 'string' &&
  6444. ((extension !== '' && identifier.endsWith(extension)) ||
  6445. (extension === '' && identifier.indexOf('.') === -1))) ||
  6446. (extension instanceof RegExp && extension.exec(identifier))) {
  6447. accept = true;
  6448. break;
  6449. }
  6450. }
  6451. this._host.event('model_file', {
  6452. file_extension: extension,
  6453. file_size: size || 0,
  6454. file_accept: accept ? 1 : 0
  6455. });
  6456. return accept;
  6457. }
  6458. _filter(context) {
  6459. const identifier = context.identifier.toLowerCase().split('/').pop();
  6460. const stream = context.stream;
  6461. if (stream) {
  6462. const buffer = stream.peek(Math.min(4096, stream.length));
  6463. const content = String.fromCharCode.apply(null, buffer);
  6464. const list = this._factories.filter((entry) =>
  6465. (typeof entry.extension === 'string' && identifier.endsWith(entry.extension)) ||
  6466. (entry.extension instanceof RegExp && entry.extension.test(identifier)) ||
  6467. (entry.content instanceof RegExp && entry.content.test(content)));
  6468. return Array.from(new Set(list.map((entry) => entry.module)));
  6469. }
  6470. return [];
  6471. }
  6472. async _openSignature(context) {
  6473. const stream = context.stream;
  6474. if (stream) {
  6475. let empty = true;
  6476. let position = 0;
  6477. while (position < stream.length) {
  6478. const buffer = stream.read(Math.min(4096, stream.length - position));
  6479. position += buffer.length;
  6480. if (!buffer.every((value) => value === 0x00)) {
  6481. empty = false;
  6482. break;
  6483. }
  6484. }
  6485. stream.seek(0);
  6486. if (empty) {
  6487. throw new view.Error('File has no content.');
  6488. }
  6489. /* eslint-disable no-control-regex */
  6490. const entries = [
  6491. { name: 'AES Crypt data', value: /^AES[\x01|\x02]\x00/ },
  6492. { name: 'AppleDouble data', value: /^\x00\x05\x16\x07/ },
  6493. { name: 'base64 data', value: /^gAAAAAB/ },
  6494. { name: 'Bash script', value: /^(#!\/usr\/bin\/env|#!\/bin\/bash)\s/ },
  6495. { name: 'BCNN model', value: /^BCNN/ },
  6496. { name: 'BModel data', value: /^\xEE\xAA\x55\xFF/ }, // https://github.com/sophgo/tpu-mlir/blob/master/include/tpu_mlir/Builder/BM168x/bmodel.fbs
  6497. { name: 'Cambricon model', value: /^\x7fMEF/ },
  6498. { name: 'Cambricon model', value: /^cambricon_offline/ },
  6499. { name: 'CviModel data', value: /^CviModel/ }, // https://github.com/sophgo/tpu-mlir/blob/master/include/tpu_mlir/Builder/CV18xx/proto/cvimodel.fbs
  6500. { name: 'DRTcrypt data', value: /^DRTcrypt/ },
  6501. { name: 'ELF executable', value: /^\x7FELF/ },
  6502. { name: 'EDL2 data', value: /^EDL2/ },
  6503. { name: 'encrypted data', value: /^ENCRYPTED_FILE|EV_ENCRYPTED/ },
  6504. { name: 'encrypted data', value: /^Salted__/ },
  6505. { name: 'encrypted data', value: /^KINGSOFTOFFICE/ },
  6506. { name: 'GGML data', value: /^lmgg|fmgg|tjgg|algg|fugg/ },
  6507. { name: 'Git LFS header', value: /^\s*oid sha256:/ },
  6508. { name: 'Git LFS header', value: /^version https:\/\/git-lfs.github.com/ },
  6509. { name: 'HTML markup', value: /^\s*<!(doctype|DOCTYPE)\s*(html|HTML)>/ },
  6510. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML\s+(PUBLIC|SYSTEM)?/ },
  6511. { name: 'HTML markup', value: /^\s*<(html|HTML)(\s+[^>]+)?>/ },
  6512. { name: 'Keras Tokenizer data', value: /^"{\\"class_name\\":\s*\\"Tokenizer\\"/ },
  6513. { name: 'llama2.c checkpoint', value: /^..\x00\x00..\x00\x00..\x00\x00..\x00\x00..\x00\x00..\x00\x00..\x00\x00/, identifier: /^stories\d+[KM]\.bin/ },
  6514. { name: 'Mathematica Notebook data', value: /^\(\*\sContent-type:\sapplication\/vnd\.wolfram\.mathematica\s\*\)/ },
  6515. { name: 'obfuscated data', value: /^obfs/ },
  6516. { name: 'Optimium model', value: /^EZMODEL/ }, // https://github.com/EZ-Optimium/Optimium,
  6517. { name: 'PNG image', value: /^\x89PNG/ },
  6518. { name: 'Python source code', value: /^((#.*(\n|\r\n))|('''.*'''(\n|\r\n))|("""[\s\S]*""")|(\n|\r\n))*(from[ ]+([a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*)[ ]+import[ ]+[a-zA-Z]\w*)/ },
  6519. { name: 'Python source code', value: /^((#.*(\n|\r\n))|('''.*'''(\n|\r\n))|("""[\s\S]*""")|(\n|\r\n))*(import[ ]+[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*([ ]+as[ ]+[a-zA-Z]\w*)?[ ]*(,|;|\n|\r\n))/ },
  6520. { name: 'Python virtual environment configuration', value: /^home[ ]*=[ ]*/, identifier: /^pyvenv\.cfg/ },
  6521. { name: 'Rich Text Format data', value: /^{\\rtf/ },
  6522. { name: 'SenseTime model', value: /^STEF/ },
  6523. { name: 'SQLite data', value: /^SQLite format/ },
  6524. { name: 'TensorFlow Hub module', value: /^\x08\x03$/, identifier: /^tfhub_module\.pb/ },
  6525. { name: 'Tokenizer data', value: /^IQ== 0\n/ },
  6526. { name: 'TSD header', value: /^%TSD-Header-###%/ },
  6527. { name: 'undocumented HALCON model', value: /^HDLMODEL/ },
  6528. { name: 'undocumented license data', value: /^This model and the software may not be used or distributed in any manner except as authorized under a valid written agreemen/ },
  6529. { name: 'undocumented NNC data', value: /^(\xC0|\xBC)\x0F\x00\x00ENNC/ },
  6530. { name: 'undocumented RKNX data', value: /^RKNX\x00\x00\x00\x00/ },
  6531. { name: 'V8 context snapshot', value: /^.\x00\x00\x00.\x00\x00\x00/, identifier: /^v8_context_snapshot\.bin/ },
  6532. { name: 'V8 natives blob', value: /^./, identifier: /^natives_blob\.bin/ },
  6533. { name: 'V8 snapshot', value: /^.\x00\x00\x00.\x00\x00\x00/, identifier: /^snapshot_blob\.bin/ },
  6534. { name: 'ViSQOL model', value: /^svm_type\s/ },
  6535. { name: 'VNN model', value: /^\x2F\x4E\x00\x00.\x00\x00\x00/, identifier: /.vnnmodel$/ },
  6536. { name: 'Windows executable', value: /^MZ[\s\S]*PE\x00\x00/ },
  6537. ];
  6538. /* eslint-enable no-control-regex */
  6539. const buffer = stream.peek(Math.min(4096, stream.length));
  6540. const content = String.fromCharCode.apply(null, buffer);
  6541. for (const entry of entries) {
  6542. if (content.match(entry.value) && (!entry.identifier || context.identifier.match(entry.identifier))) {
  6543. throw new view.Error(`Invalid file content. File contains ${entry.name}.`);
  6544. }
  6545. }
  6546. }
  6547. }
  6548. async import() {
  6549. if (this._host.type === 'Browser' || this._host.type === 'Python') {
  6550. const files = [
  6551. './message', './onnx', './pytorch', './tflite', './mlnet',
  6552. './onnx-proto', './onnx-schema', './tflite-schema',
  6553. 'onnx-metadata.json', 'pytorch-metadata.json', 'tflite-metadata.json'
  6554. ];
  6555. for (const file of files) {
  6556. /* eslint-disable no-await-in-loop */
  6557. try {
  6558. if (file.startsWith('./')) {
  6559. await this._host.require(file);
  6560. } else if (file.endsWith('.json')) {
  6561. await this._host.request(file, 'utf-8', null);
  6562. }
  6563. } catch {
  6564. // continue regardless of error
  6565. }
  6566. /* eslint-enable no-await-in-loop */
  6567. }
  6568. }
  6569. }
  6570. };
  6571. view.Metadata = class {
  6572. static async open(context, name) {
  6573. view.Metadata._metadata = view.Metadata._metadata || new Map();
  6574. const metadata = view.Metadata._metadata;
  6575. if (!metadata.has(name)) {
  6576. let data = null;
  6577. try {
  6578. data = await context.request(name);
  6579. } catch {
  6580. // continue regardless of error
  6581. }
  6582. const types = JSON.parse(data);
  6583. metadata.set(name, new view.Metadata(types));
  6584. }
  6585. return metadata.get(name);
  6586. }
  6587. constructor(types) {
  6588. this._types = new Map();
  6589. this._attributes = new Map();
  6590. this._inputs = new Map();
  6591. if (Array.isArray(types)) {
  6592. for (const type of types) {
  6593. if (this._types.has(type.name)) {
  6594. // throw new view.Error(`Duplicate type metadata '${type.name}'.`);
  6595. }
  6596. this._types.set(type.name, type);
  6597. if (type.identifier !== undefined) {
  6598. this._types.set(type.identifier, type);
  6599. }
  6600. }
  6601. }
  6602. }
  6603. type(name) {
  6604. if (!this._types.has(name)) {
  6605. this._types.set(name, { name: name.toString() });
  6606. }
  6607. return this._types.get(name);
  6608. }
  6609. attribute(type, name) {
  6610. const key = `${type}:${name}`;
  6611. if (!this._attributes.has(key)) {
  6612. this._attributes.set(key, null);
  6613. const metadata = this.type(type);
  6614. if (metadata && Array.isArray(metadata.attributes)) {
  6615. for (const attribute of metadata.attributes) {
  6616. this._attributes.set(`${type}:${attribute.name}`, attribute);
  6617. }
  6618. }
  6619. }
  6620. return this._attributes.get(key);
  6621. }
  6622. input(type, name) {
  6623. const key = `${type}:${name}`;
  6624. if (!this._inputs.has(key)) {
  6625. this._inputs.set(key, null);
  6626. const metadata = this.type(type);
  6627. if (metadata && Array.isArray(metadata.inputs)) {
  6628. for (const input of metadata.inputs) {
  6629. this._inputs.set(`${type}:${input.name}`, input);
  6630. }
  6631. }
  6632. }
  6633. return this._inputs.get(key);
  6634. }
  6635. };
  6636. view.Error = class extends Error {
  6637. constructor(message) {
  6638. super(message);
  6639. this.name = 'Error loading model.';
  6640. }
  6641. };
  6642. if (typeof window !== 'undefined' && window.exports) {
  6643. window.exports.view = view;
  6644. }
  6645. export const View = view.View;
  6646. export const ModelFactoryService = view.ModelFactoryService;
  6647. export const ModelSidebar = view.ModelSidebar;
  6648. export const NodeSidebar = view.NodeSidebar;
  6649. export const TensorSidebar = view.TensorSidebar;
  6650. export const Documentation = view.Documentation;
  6651. export const Formatter = view.Formatter;
  6652. export const Tensor = view.Tensor;
  6653. export const Quantization = view.Quantization;