view.js 305 KB

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