view.js 302 KB

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