view.js 302 KB

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