vwf.js 238 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2020 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. Virtual World Framework Apache 2.0 license (https://github.com/NikolaySuslov/livecodingspace/blob/master/licenses/LICENSE_VWF.md)
  5. */
  6. /// @module vwf
  7. /// vwf.js is the main Virtual World Framework manager. It is constructed as a JavaScript ES6 module
  8. /// to isolate it from the rest of the page's JavaScript environment. The vwf module self-creates its own instance when loaded and
  9. /// attaches to the global window object as window.vwf. Nothing else should affect the global environment.
  10. import { Helpers } from '/core/helpers.js';
  11. import { VirtualTime } from '/core/virtualTime.js';
  12. import { ReflectorClient } from '/core/reflectorClient.js';
  13. import { Luminary } from '/core/luminary.js';
  14. import { Logger } from '/core/vwf/utility/logger.js';
  15. import { KUtility } from '/core/vwf/utility/kutility.js';
  16. import { Utility } from '/core/vwf/utility/utility.js';
  17. import { XPath } from '/core/vwf/utility/xpath.js';
  18. import { Fabric } from '/core/vwf/fabric.js';
  19. import { ViewKernel } from '/core/vwf/view.js';
  20. import { ModelKernel } from '/core/vwf/model.js';
  21. import { Log } from '/core/vwf/model/stage/log.js';
  22. class VWF {
  23. constructor(driverConf, proxy, doc, connectionConf) {
  24. console.log("VWF constructor");
  25. let self = this;
  26. this.helpers = new Helpers;
  27. this.driverConfiguration = driverConf || {};
  28. this.proxy = proxy;
  29. this.doc = doc;
  30. this.isLuminary = connectionConf.luminary;
  31. this.isLuminaryGlobalHB = connectionConf.luminaryHB;
  32. this.luminaryGlobalHBPath = connectionConf.luminaryGlobalHBPath;
  33. this.luminary = new Luminary;
  34. this.reflectorClient = new ReflectorClient;
  35. this.virtualTime = new VirtualTime;
  36. window._Time = this.virtualTime; //vwf.virtualTime = app.virtualTime;
  37. this.applicationLoad = undefined;
  38. // == Public variables =====================================================================
  39. /// The runtime environment (production, development, testing) and other configuration
  40. /// settings appear here.
  41. ///
  42. /// @name module:vwf.configuration
  43. ///
  44. /// @private
  45. /// Default configuration for all environments.
  46. this.configuration = {
  47. "log-level": "info", // logger threshold
  48. "random-seed": +new Date, // pseudorandom number generator seed
  49. "randomize-ids": true, // randomize IDs to discourage assumptions about ID allocation
  50. "humanize-ids": true, // append recognizable strings to node IDs
  51. "preserve-script-closures": false, // retain method/event closures by not serializing functions (breaks replication, persistence)
  52. "load-timeout": 30 // resource load timeout in seconds
  53. }
  54. //undefined; // require( "vwf/configuration" ).active; // "active" updates in place and changes don't invalidate the reference // TODO: assign here after converting vwf.js to a RequireJS module and listing "vwf/configuration" as a dependency
  55. /// Kernel utility functions and objects.
  56. ///
  57. /// @name module:vwf.utility
  58. ///
  59. /// @private
  60. this.kutility = new KUtility;
  61. //this.kutility = undefined; // require( "vwf/kernel/utility" ); // TODO: assign here after converting vwf.js to a RequireJS module and listing "vwf/kernel/utility" as a dependency
  62. this.xpath = new XPath;
  63. this.utility = new Utility;
  64. this.viewModule = new Fabric({
  65. id:"vwf/view"
  66. }, 'View');
  67. this.modelModule = new Fabric({
  68. id:"vwf/model"
  69. }, 'Model');
  70. /// The kernel logger.
  71. ///
  72. /// @name module:vwf.logger
  73. ///
  74. /// @private
  75. this.logger = (new Logger).for("vwf", this, this.configuration["log-level"] );
  76. //undefined; // require( "logger" ).for( undefined, this ); // TODO: for( "vwf", ... ), and update existing calls // TODO: assign here after converting vwf.js to a RequireJS module and listing "vwf/logger" as a dependency
  77. /// Each model and view module loaded by the main page registers itself here.
  78. ///
  79. /// @name module:vwf.modules
  80. ///
  81. /// @private
  82. this.modules = [];
  83. /// vwf.initialize() creates an instance of each model and view module configured on the main
  84. /// page and attaches them here.
  85. ///
  86. /// @name module:vwf.models
  87. ///
  88. /// @private
  89. this.models = [];
  90. /// vwf.initialize() creates an instance of each model and view module configured on the main
  91. /// page and attaches them here.
  92. ///
  93. /// @name module:vwf.views
  94. ///
  95. /// @private
  96. this.views = [];
  97. /// this.models is a list of references to the head of each driver pipeline. Define an
  98. /// `actual` property that evaluates to a list of references to the pipeline tails. This is
  99. /// a list of the actual drivers after any intermediate stages and is useful for debugging.
  100. ///
  101. /// @name module:vwf.models.actual
  102. Object.defineProperty(this.models, "actual", {
  103. get: function () {
  104. // Map the array to the result.
  105. var actual = this.map(function (model) {
  106. return last(model);
  107. });
  108. // Map the non-integer properties too.
  109. for (var propertyName in this) {
  110. if (isNaN(Number(propertyName))) {
  111. actual[propertyName] = last(this[propertyName]);
  112. }
  113. }
  114. // Follow a pipeline to the last stage.
  115. function last(model) {
  116. while (model.model) model = model.model;
  117. return model;
  118. }
  119. return actual;
  120. }
  121. });
  122. /// this.views is a list of references to the head of each driver pipeline. Define an
  123. /// `actual` property that evaluates to a list of references to the pipeline tails. This is
  124. /// a list of the actual drivers after any intermediate stages and is useful for debugging.
  125. ///
  126. /// @name module:vwf.views.actual
  127. Object.defineProperty(this.views, "actual", {
  128. get: function () {
  129. // Map the array to the result.
  130. var actual = this.map(function (model) {
  131. return last(model);
  132. });
  133. // Map the non-integer properties too.
  134. for (var propertyName in this) {
  135. if (isNaN(Number(propertyName))) {
  136. actual[propertyName] = last(this[propertyName]);
  137. }
  138. }
  139. // Follow a pipeline to the last stage.
  140. function last(model) {
  141. while (model.model) model = model.model;
  142. return model;
  143. }
  144. return actual;
  145. }
  146. });
  147. /// The identifer assigned to the client by the server.
  148. ///
  149. /// @name module:vwf.moniker_
  150. ///
  151. /// @private
  152. this.moniker_ = undefined;
  153. /// Nodes that are receiving ticks.
  154. ///
  155. /// @name module:vwf.tickable
  156. ///
  157. /// @private
  158. this.tickable = {
  159. // models: [],
  160. // views: [],
  161. nodeIDs: [],
  162. };
  163. // == Private variables ====================================================================
  164. /// @name module:vwf.private
  165. ///
  166. /// @private
  167. this.private = {}; // for debugging
  168. /// Components describe the objects that make up the simulation. They may also serve as
  169. /// prototype objects for further derived components. External components are identified by
  170. /// URIs. Once loaded, we save a mapping here from its URI to the node ID of its prototype so
  171. /// that we can find it if it is reused. Components specified internally as object literals
  172. /// are anonymous and are not indexed here.
  173. ///
  174. /// @name module:vwf~components
  175. this.components = this.private.components = {}; // maps component node ID => component specification
  176. // Each node is assigned an ID as it is created. This is the most recent ID assigned.
  177. // Communication between the manager and the models and views uses these IDs to refer to the
  178. // nodes. The manager doesn't maintain any particular state for the nodes and knows them
  179. // only as their IDs. The models work in federation to provide the meaning to each node.
  180. // var lastID = 0;
  181. /// Callback functions defined in this scope use this local "vwf" to locate the manager.
  182. ///
  183. /// @name module:vwf~vwf
  184. window.vwf = this;
  185. //////////
  186. this.setProperty.entrants = {}; // maps ( nodeID + '-' + propertyName ) => { index: i, value: v }
  187. this.getProperty.entrants = {}; // maps ( nodeID + '-' + propertyName ) => { index: i, value: v }
  188. // == Private variables ====================================================================
  189. /// Prototype for name-based, unordered collections in the node registry, including
  190. /// `node.properties`, `node.methods`, and `node.events`.
  191. this.keyedCollectionPrototype = {
  192. /// Record that a property, method or event has been created.
  193. ///
  194. /// @param {String} name
  195. /// The member name.
  196. /// @param {Boolean} changes
  197. /// For patchable nodes, record changes so that `kernel.getNode` may create a patch
  198. /// when retrieving the node.
  199. /// @param [value]
  200. /// An optional value to assign to the record. If `value` is omitted, the record will
  201. /// exist in the collection but have the value `undefined`.
  202. ///
  203. /// @returns {Boolean}
  204. /// `true` if the member was successfully added. `false` if a member by that name
  205. /// already exists.
  206. create: function (name, changes, value) {
  207. if (!this.hasOwn(name)) {
  208. this.makeOwn("existing");
  209. // Add the member. `Object.defineProperty` is used instead of
  210. // `this.existing[name] = ...` since the prototype may be a behavior proxy, and
  211. // the accessor properties would prevent normal assignment.
  212. Object.defineProperty(this.existing, name,
  213. self.configurable(value ? value : undefined));
  214. if (changes) {
  215. this.makeOwn("changes");
  216. if (this.changes[name] !== "removed") {
  217. this.changes[name] = "added";
  218. } else {
  219. this.changes[name] = "changed"; // previously removed, then added
  220. }
  221. if (this.container && this.containerMember) {
  222. this.container.change(this.containerMember);
  223. }
  224. }
  225. return true;
  226. }
  227. return false;
  228. },
  229. /// Record that a member has been deleted.
  230. ///
  231. /// @param {String} name
  232. /// The member name.
  233. ///
  234. /// @returns {Boolean}
  235. /// `true` if the member was successfully removed. `false` if a member by that name
  236. /// does not exist.
  237. delete: function (name, changes) {
  238. if (this.hasOwn(name)) {
  239. delete this.existing[name];
  240. if (changes) {
  241. this.makeOwn("changes");
  242. if (this.changes[name] !== "added") {
  243. this.changes[name] = "removed";
  244. } else {
  245. delete this.changes[name]; // previously added, then removed
  246. }
  247. if (this.container && this.containerMember) {
  248. this.container.change(this.containerMember);
  249. }
  250. }
  251. return true;
  252. }
  253. return false;
  254. },
  255. /// Record that a member has changed.
  256. ///
  257. /// @param {String} name
  258. /// The member name.
  259. ///
  260. /// @returns {Boolean}
  261. /// `true` if the change was successfully recorded. `false` if a member by that name
  262. /// does not exist.
  263. change: function (name, value) {
  264. if (this.hasOwn(name)) {
  265. this.makeOwn("changes");
  266. if (this.changes[name] !== "added") {
  267. this.changes[name] = value ?
  268. value : this.changes[name] || "changed";
  269. }
  270. if (this.container && this.containerMember) {
  271. this.container.change(this.containerMember);
  272. }
  273. return true;
  274. }
  275. return false;
  276. },
  277. /// Determine if a node has a member with the given name, either directly on the node or
  278. /// inherited from a prototype.
  279. ///
  280. /// @param {String} name
  281. /// The member name.
  282. ///
  283. /// @returns {Boolean}
  284. has: function (name) {
  285. return name in this.existing;
  286. },
  287. /// Determine if a node has a member with the given name. The node's prototypes are not
  288. /// considered.
  289. ///
  290. /// @param {String} name
  291. /// The member name.
  292. ///
  293. /// @returns {Boolean}
  294. // Since prototypes of the collection objects mirror the node's prototype chain,
  295. // collection objects for the proto-prototype `node.vwf` intentionally don't inherit
  296. // from `Object.prototype`. Otherwise the Object members `hasOwnProperty`,
  297. // `isPrototypeOf`, etc. would be mistaken as members of a VWF node.
  298. // Instead of using the simpler `this.existing.hasOwnProperty( name )`, we must reach
  299. // `hasOwnProperty through `Object.prototype`.
  300. hasOwn: function (name) {
  301. return Object.prototype.hasOwnProperty.call(this.existing, name);
  302. },
  303. /// Hoist a field from a prototype to the collection in preparation for making local
  304. /// changes.
  305. ///
  306. /// If the field in the prototype is an object, create a new object with that field as
  307. /// its prototype. If the field in the prototype is an array, clone the field since
  308. /// arrays can't readily serve as prototypes for other arrays. In other cases, copy the
  309. /// field from the prototype. Only objects, arrays and primitive values are supported.
  310. ///
  311. /// @param {String} fieldName
  312. /// The name of a field to hoist from the collection's prototype.
  313. makeOwn: function (fieldName) {
  314. if (!this.hasOwnProperty(fieldName)) {
  315. if (this[fieldName] instanceof Array) {
  316. this[fieldName] = this[fieldName].slice(); // clone arrays
  317. } else if (typeof this[fieldName] === "object" && this[fieldName] !== null) {
  318. this[fieldName] = Object.create(this[fieldName]); // inherit from objects
  319. } else {
  320. this[fieldName] = this[fieldName]; // copy primitives
  321. }
  322. }
  323. },
  324. /// The property, method, or event members defined in this collection.
  325. ///
  326. /// `existing` is an unordered collection of elements and optional values. The keys are
  327. /// the primary data. Existence on the object is significant regardless of the value.
  328. /// Some collections store data in the element when the kernel owns additional details
  329. /// about the member. Values will be `undefined` in other collections.
  330. ///
  331. /// For each collection, `existing` is the authoritative list of the node's members. Use
  332. /// `collection.hasOwn( memberName )` to determine if the node defines a property,
  333. /// method or event by that name.
  334. ///
  335. /// The prototype of each `existing` object will be the `existing` object of the node's
  336. /// prototype (or a proxy to the top behavior for nodes with behaviors). Use
  337. /// `collection.has( memberName )` to determine if a property, method or event is
  338. /// defined on the node or its prototypes.
  339. existing: Object.create(null
  340. // name: undefined,
  341. // name: { ... } -- details
  342. // ...
  343. ),
  344. /// The change list for members in this collection.
  345. ///
  346. /// For patchable nodes, `changes` records the members that have been added, removed, or
  347. /// changed since the node was first initialized. `changes` is not created in the
  348. /// collection until the first change occurs. Only the change is recorded here. The
  349. /// state behind the change is retrieved from the drivers when needed.
  350. changes: {
  351. // name: "added"
  352. // name: "removed"
  353. // name: "changed"
  354. // name: { ... } -- changed, with details
  355. // ...
  356. },
  357. /// The parent collection if this collection is a member of another. Changes applied to
  358. /// members of this collection will call `container.change( containerMember )` to also
  359. /// set the change flag for the containing member.
  360. ///
  361. /// For example, members of the `node.events` collection contain listener collections at
  362. /// `node.events.existing[name].listeners`. Each listener collection knows its event
  363. /// name and points back to `node.events`. Changing a listener will call
  364. /// `node.events.change( name )` to mark the event as changed.
  365. container: undefined,
  366. /// This collection's name in the parent if this collection is a member of another
  367. /// collection. Changes to members of this collection will mark that member changed in
  368. /// the containing collection.
  369. containerMember: undefined,
  370. }
  371. /// Prototype for index-based, ordered collections in the node registry, including
  372. /// `event.listeners`.
  373. this.indexedCollectionPrototype = {
  374. /// Record that a member has been created.
  375. ///
  376. /// @param {string|number|boolean|null} id
  377. /// The member's unique id.
  378. /// @param {Boolean} changes
  379. /// For patchable nodes, record changes so that `kernel.getNode` may create a patch
  380. /// when retrieving the node.
  381. ///
  382. /// @returns {Boolean}
  383. /// `true` if the member was successfully added. `false` if a member with that id
  384. /// already exists.
  385. create: function (id, changes) {
  386. if (!this.hasOwn(id)) {
  387. this.makeOwn("existing");
  388. this.existing.push(id);
  389. if (changes) {
  390. this.makeOwn("changes");
  391. var removedIndex = this.changes.removed ?
  392. this.changes.removed.indexOf(id) : -1;
  393. if (removedIndex < 0) {
  394. this.changes.added = this.changes.added || [];
  395. this.changes.added.push(id);
  396. } else {
  397. this.changes.removed.splice(removedIndex, 1);
  398. this.changes.changed = this.changes.changed || [];
  399. this.changes.changed.push(id);
  400. }
  401. if (this.container && this.containerMember) {
  402. this.container.change(this.containerMember);
  403. }
  404. }
  405. return true;
  406. }
  407. return false;
  408. },
  409. /// Record that a member has been deleted.
  410. ///
  411. /// @param {string|number|boolean|null} id
  412. /// The member's unique id.
  413. ///
  414. /// @returns {Boolean}
  415. /// `true` if the member was successfully removed. `false` if a member with that id
  416. /// does not exist.
  417. delete: function (id, changes) {
  418. if (this.hasOwn(id)) {
  419. this.existing.splice(this.existing.indexOf(id), 1);
  420. if (changes) {
  421. this.makeOwn("changes");
  422. var addedIndex = this.changes.added ?
  423. this.changes.added.indexOf(id) : -1;
  424. if (addedIndex < 0) {
  425. this.changes.removed = this.changes.removed || [];
  426. this.changes.removed.push(id);
  427. } else {
  428. this.changes.added.splice(addedIndex, 1);
  429. }
  430. if (this.container && this.containerMember) {
  431. this.container.change(this.containerMember);
  432. }
  433. }
  434. return true;
  435. }
  436. return false;
  437. },
  438. /// Record that a member has changed.
  439. ///
  440. /// @param {string|number|boolean|null} id
  441. /// The member's unique id.
  442. ///
  443. /// @returns {Boolean}
  444. /// `true` if the change was successfully recorded. `false` if a member with that id
  445. /// does not exist.
  446. change: function (id) {
  447. if (this.hasOwn(id)) {
  448. this.makeOwn("changes");
  449. var addedIndex = this.changes.added ?
  450. this.changes.added.indexOf(id) : -1;
  451. var changedIndex = this.changes.changed ?
  452. this.changes.changed.indexOf(id) : -1;
  453. if (addedIndex < 0 && changedIndex < 0) {
  454. this.changes.changed = this.changes.changed || [];
  455. this.changes.changed.push(id);
  456. }
  457. if (this.container && this.containerMember) {
  458. this.container.change(this.containerMember);
  459. }
  460. return true;
  461. }
  462. return false;
  463. },
  464. /// Determine if a node has a member with the given id.
  465. ///
  466. /// `has` is the same as `hasOwn` for `indexedCollectionPrototype` since index-based
  467. /// collections don't automatically inherit from their prototypes.
  468. ///
  469. /// @param {string|number|boolean|null} id
  470. /// The member's unique id.
  471. ///
  472. /// @returns {Boolean}
  473. has: function (id) {
  474. return this.hasOwn(id);
  475. },
  476. /// Determine if a node has a member with the given id. The node's prototypes are not
  477. /// considered.
  478. ///
  479. /// @param {string|number|boolean|null} id
  480. /// The member's unique id.
  481. ///
  482. /// @returns {Boolean}
  483. hasOwn: function (id) {
  484. return this.existing ? this.existing.indexOf(id) >= 0 : false;
  485. },
  486. /// Hoist a field from a prototype to the collection in preparation for making local
  487. /// changes.
  488. ///
  489. /// If the field in the prototype is an object, create a new object with that field as
  490. /// its prototype. If the field in the prototype is an array, clone the field since
  491. /// arrays can't readily serve as prototypes for other arrays. In other cases, copy the
  492. /// field from the prototype. Only objects, arrays and primitive values are supported.
  493. ///
  494. /// @param {String} fieldName
  495. /// The name of a field to hoist from the collection's prototype.
  496. makeOwn: function (fieldName) {
  497. if (!this.hasOwnProperty(fieldName)) {
  498. if (this[fieldName] instanceof Array) {
  499. this[fieldName] = this[fieldName].slice(); // clone arrays
  500. } else if (typeof this[fieldName] === "object" && this[fieldName] !== null) {
  501. this[fieldName] = Object.create(this[fieldName]); // inherit from objects
  502. } else {
  503. this[fieldName] = this[fieldName]; // copy primitives
  504. }
  505. }
  506. },
  507. /// IDs of the members defined in this collection.
  508. ///
  509. /// `existing` is an ordered list of IDs, which much be unique within the collection.
  510. /// The IDs retain the order in which they were originally added.
  511. ///
  512. /// For each collection, `existing` is the authoritative list of the node's members. Use
  513. /// `collection.hasOwn( memberID )` to determine if the collection contains a member
  514. /// with that id. Unlike `keyedCollectionPrototype` collections,
  515. /// `indexedCollectionPrototype` collections aren't connected in parallel with their
  516. /// containers' prototype chains.
  517. existing: [
  518. // id,
  519. // id,
  520. // ...
  521. ],
  522. /// The change list for members in this collection.
  523. ///
  524. /// For patchable nodes, `changes` records the members that have been added, removed, or
  525. /// changed since the node was first initialized. Changes are recorded in separate
  526. /// `added`, `removed`, and `changed` arrays, respectively. The `added` array retains
  527. /// the order in which the members were added. Although `removed` and `changed` are also
  528. /// arrays, the order of removals and changes is not significant.
  529. ///
  530. /// `changes` is not created in the collection until the first change occurs. Only the
  531. /// change is recorded here. The state behind the change is retrieved from the drivers
  532. /// when needed.
  533. changes: {
  534. // added: [ id, ... ],
  535. // removed: [ id, ... ],
  536. // changed: [ id, ... ],
  537. },
  538. /// The parent collection if this collection is a member of another. Changes applied to
  539. /// members of this collection will call `container.change( containerMember )` to also
  540. /// set the change flag for the containing member.
  541. ///
  542. /// For example, members of the `node.events` collection contain listener collections at
  543. /// `node.events.existing[name].listeners`. Each listener collection knows its event
  544. /// name and points back to `node.events`. Changing a listener will call
  545. /// `node.events.change( name )` to mark the event as changed.
  546. container: undefined,
  547. /// This collection's name in the parent if this collection is a member of another
  548. /// collection. Changes to members of this collection will mark that member changed in
  549. /// the containing collection.
  550. containerMember: undefined,
  551. }
  552. // Prototype for the `events` collection in the `nodes` objects.
  553. this.eventCollectionPrototype = Object.create(self.keyedCollectionPrototype, {
  554. create: {
  555. value: function (name, changes, parameters) {
  556. var value = parameters ? {
  557. parameters: parameters.slice(), // clone
  558. } : {};
  559. value.listeners = Object.create(self.indexedCollectionPrototype, {
  560. container: self.enumerable(this),
  561. containerMember: self.enumerable(name),
  562. });
  563. return self.keyedCollectionPrototype.create.call(this, name, changes, value);
  564. }
  565. },
  566. })
  567. /// The application's nodes, indexed by ID.
  568. ///
  569. /// The kernel defines an application as:
  570. ///
  571. /// * A tree of nodes,
  572. /// * Extending prototypes and implementing behaviors,
  573. /// * Publishing properties, and
  574. /// * Communicating using methods and events.
  575. ///
  576. /// This definition is as abstract as possible to avoid imposing unnecessary policy on the
  577. /// application. The concrete realization of these concepts lives in the hearts and minds of
  578. /// the drivers configured for the application. `nodes` contains the kernel's authoritative
  579. /// data about this arrangement.
  580. ///
  581. /// @name module:vwf~nodes
  582. // Note: this is a first step towards moving authoritative data out of the vwf/model/object
  583. // and vwf/model/javascript drivers and removing the kernel's dependency on them as special
  584. // cases. Only `nodes.existing[id].properties` is currently implemented this way.
  585. this.nodes = this.private.nodes = {
  586. /// Register a node as it is created.
  587. ///
  588. /// @param {ID} nodeID
  589. /// The ID assigned to the new node. The node will be indexed in `nodes` by this ID.
  590. /// @param {ID} prototypeID
  591. /// The ID of the node's prototype, or `undefined` if this is the proto-prototype,
  592. /// `node.vwf`.
  593. /// @param {ID[]} behaviorIDs
  594. /// An array of IDs of the node's behaviors. `behaviorIDs` should be an empty array if
  595. /// the node doesn't have any behaviors.
  596. /// @param {String} nodeURI
  597. /// The node's URI. `nodeURI` should be the component URI if this is the root node of
  598. /// a component loaded from a URI, and undefined in all other cases.
  599. /// @param {String} nodeName
  600. /// The node's name.
  601. /// @param {ID} parentID
  602. /// The ID of the node's parent, or `undefined` if this is the application root node
  603. /// or another global, top-level node.
  604. ///
  605. /// @returns {Object}
  606. /// The kernel `node` object if the node was successfully added. `undefined` if a node
  607. /// identified by `nodeID` already exists.
  608. create: function (nodeID, prototypeID, behaviorIDs, nodeURI, nodeName, parentID) {
  609. // if ( ! this.existing[nodeID] ) {
  610. let selfNode = this;
  611. var prototypeNode = behaviorIDs.reduce(function (prototypeNode, behaviorID) {
  612. return selfNode.proxy(prototypeNode, selfNode.existing[behaviorID]);
  613. }, this.existing[prototypeID]);
  614. // Look up the parent.
  615. var parentNode = this.existing[parentID];
  616. // If this is the global root of a new tree, add it to the `globals` set.
  617. if (!parentNode) {
  618. this.globals[nodeID] = undefined;
  619. }
  620. // Add the node to the registry.
  621. return this.existing[nodeID] = {
  622. // id: ...,
  623. // Inheritance. -- not implemented here yet; still using vwf/model/object
  624. // prototype: ...,
  625. // behaviors: [],
  626. // Intrinsic state. -- not implemented here yet.
  627. // source: ...,
  628. // type: ...,
  629. uri: nodeURI,
  630. name: nodeName,
  631. // Internal state. The change flags are omitted until needed. -- not implemented here yet; still using vwf/model/object
  632. // sequence: ...,
  633. // sequenceChanged: true / false,
  634. // prng: ...,
  635. // prngChanged: true / false,
  636. // Tree. -- not implemented here yet; still using vwf/model/object
  637. // parent: ...,
  638. // children: [],
  639. // Property, Method and Event members defined on the node.
  640. properties: Object.create(self.keyedCollectionPrototype, {
  641. existing: self.enumerable(Object.create(prototypeNode ?
  642. prototypeNode.properties.existing : null)),
  643. }),
  644. methods: Object.create(self.keyedCollectionPrototype, {
  645. existing: self.enumerable(Object.create(prototypeNode ?
  646. prototypeNode.methods.existing : null)),
  647. }),
  648. events: Object.create(self.eventCollectionPrototype, {
  649. existing: self.enumerable(Object.create(prototypeNode ?
  650. prototypeNode.events.existing : null)),
  651. }),
  652. // Is this node patchable? Nodes are patchable if they were loaded from a
  653. // component.
  654. patchable: !!(nodeURI ||
  655. parentNode && !parentNode.initialized && parentNode.patchable),
  656. // Has this node completed initialization? For applications, visibility to
  657. // ancestors from uninitialized nodes is blocked. Change tracking starts
  658. // after initialization.
  659. initialized: false,
  660. childsDeleted: {}
  661. };
  662. // } else {
  663. // return undefined;
  664. // }
  665. },
  666. /// Record that a node has initialized.
  667. initialize: function (nodeID) {
  668. if (this.existing[nodeID]) {
  669. this.existing[nodeID].initialized = true;
  670. return true;
  671. }
  672. return false;
  673. },
  674. /// Unregister a node as it is deleted.
  675. delete: function (nodeID, parentID) {
  676. if (this.existing[nodeID] && this.existing[parentID]) {
  677. this.existing[parentID].childsDeleted[this.existing[nodeID].name] = nodeID;
  678. delete this.existing[nodeID];
  679. delete this.globals[nodeID];
  680. return true;
  681. }
  682. return false;
  683. },
  684. /// Create a proxy node in the form of the nodes created by `nodes.create` to represent
  685. /// a behavior node in another node's prototype chain. The `existing` objects of the
  686. /// proxy's collections link to the prototype collection's `existing` objects, just as
  687. /// with a regular prototype. The proxy's members delegate to the corresponding members
  688. /// in the behavior.
  689. proxy: function (prototypeNode, behaviorNode) {
  690. return {
  691. properties: {
  692. existing: Object.create(
  693. prototypeNode ? prototypeNode.properties.existing : null,
  694. propertyDescriptorsFor(behaviorNode.properties.existing)
  695. ),
  696. },
  697. methods: {
  698. existing: Object.create(
  699. prototypeNode ? prototypeNode.methods.existing : null,
  700. propertyDescriptorsFor(behaviorNode.methods.existing)
  701. ),
  702. },
  703. events: {
  704. existing: Object.create(
  705. prototypeNode ? prototypeNode.events.existing : null,
  706. propertyDescriptorsFor(behaviorNode.events.existing)
  707. ),
  708. },
  709. };
  710. /// Return an `Object.create` properties object for a proxy object for the provided
  711. /// collection's `existing` object.
  712. function propertyDescriptorsFor(collectionExisting) {
  713. return Object.keys(collectionExisting).reduce(
  714. function (propertiesObject, memberName) {
  715. propertiesObject[memberName] = {
  716. get: function () {
  717. return collectionExisting[memberName]
  718. },
  719. enumerable: true,
  720. };
  721. return propertiesObject;
  722. },
  723. {}
  724. );
  725. }
  726. },
  727. /// Registry of all nodes, indexed by ID. Each is an object created by `nodes.create`.
  728. existing: {
  729. // id: {
  730. // id: ...,
  731. // uri: ...,
  732. // name: ...,
  733. // ...
  734. // }
  735. },
  736. /// Global root nodes. Each of these is the root of a tree.
  737. ///
  738. /// The `globals` object is a set: the keys are the data, and only existence on the
  739. /// object is significant.
  740. globals: {
  741. // id: undefined,
  742. }
  743. }
  744. }
  745. // == Public functions =====================================================================
  746. // -- loadConfiguration ---------------------------------------------------------------------------
  747. // The main page only needs to call vwf.loadConfiguration() to launch the application. Use
  748. // require.ready() or jQuery(document).ready() to call loadConfiguration() once the page has
  749. // loaded. loadConfiguration() accepts three parameters.
  750. //
  751. // A component specification identifies the application to be loaded. modelInitializers and
  752. // viewInitializers identify the model and view libraries that were parsed out of the URL that
  753. // should be attached to the simulation. Each is specified as an object with each library
  754. // name as a property of the object with any arguments as the value of the property.
  755. // Arguments may be specified as an array [1], as a single value if there is only one [2], or as
  756. // undefined if there are none[3].
  757. //
  758. // [1] vwf.loadConfiguration( ..., { "vwf/model/glge": [ "#scene, "second param" ] }, { ... } )
  759. // [2] vwf.loadConfiguration( ..., { "vwf/model/glge": "#scene" }, { ... } )
  760. // [3] vwf.loadConfiguration( ..., { "vwf/model/javascript": undefined }, { ... } )
  761. loadConfiguration(app, userLib, cb
  762. /* [ componentURI|componentObject ] { modelInitializers }
  763. { viewInitializers } */
  764. ) {
  765. let self = this;
  766. let applicationLoad = app;
  767. let userLibraries = userLib || {};
  768. var applicationConfig = {};
  769. let callback = cb;
  770. var initializers = {
  771. model: [
  772. {
  773. library: "/core/vwf/model/ohm",
  774. active: true
  775. },
  776. {
  777. library: "/core/vwf/model/javascript",
  778. active: true
  779. },
  780. {
  781. library: "/core/vwf/model/object",
  782. active: true
  783. }
  784. ],
  785. view: [
  786. {
  787. library: "/core/vwf/view/ohm",
  788. active: true
  789. },
  790. {
  791. library: "/core/vwf/view/document",
  792. active: true
  793. },
  794. ]
  795. };
  796. //mapLibraryName(requireArray);
  797. mapLibraryName(initializers["model"]);
  798. mapLibraryName(initializers["view"]);
  799. function mapLibraryName(array) {
  800. for (var i = 0; i < array.length; i++) {
  801. array[array[i].library] = array[i];
  802. }
  803. }
  804. function getActiveLibraries(libraryList, includeParameters) {
  805. var activeLibraryList = [];
  806. for (var i = 0; i < libraryList.length; i++) {
  807. if (libraryList[i].active) {
  808. if (includeParameters) {
  809. var activeLibrary = {};
  810. activeLibrary[libraryList[i].library] = libraryList[i].parameters;
  811. activeLibraryList.push(activeLibrary);
  812. } else {
  813. activeLibraryList.push(libraryList[i].library);
  814. }
  815. }
  816. }
  817. return activeLibraryList;
  818. }
  819. // let confPromise = new Promise((resolve, reject) => {
  820. // resolve(this.driverConfiguration);
  821. // });
  822. let configLibraries = this.driverConfiguration;
  823. if (configLibraries && typeof configLibraries == "object") {
  824. if (typeof configLibraries.configuration == "object") {
  825. applicationConfig = configLibraries.configuration;
  826. }
  827. Object.keys(configLibraries).forEach(function (libraryType) {
  828. if (libraryType == 'info' && configLibraries[libraryType]["title"]) {
  829. //jQuery('title').html(configLibraries[libraryType]["title"]);
  830. document.querySelector('title').innerHTML = configLibraries[libraryType]["title"]
  831. }
  832. if (!userLibraries[libraryType]) {
  833. userLibraries[libraryType] = {};
  834. }
  835. // Merge libraries from config file and URL together. Check for incompatible
  836. // libraries, and disable them.
  837. Object.keys(configLibraries[libraryType]).forEach(function (libraryName) {
  838. var disabled = false;
  839. if (!disabled) {
  840. if (userLibraries[libraryType][libraryName] == undefined) {
  841. userLibraries[libraryType][libraryName] = configLibraries[libraryType][libraryName];
  842. } else if (typeof userLibraries[libraryType][libraryName] == "object" && typeof configLibraries[libraryType][libraryName] == "object") {
  843. userLibraries[libraryType][libraryName] = Object.assign({}, configLibraries[libraryType][libraryName], userLibraries[libraryType][libraryName]);
  844. }
  845. }
  846. });
  847. });
  848. }
  849. Object.keys(userLibraries).forEach(function (libraryType) {
  850. if (initializers[libraryType]) {
  851. Object.keys(userLibraries[libraryType]).forEach(function (libraryName) {
  852. //if (requireArray[libraryName]) {
  853. // requireArray[libraryName].active = true;
  854. if(!initializers[libraryType][libraryName]){
  855. initializers[libraryType].unshift({'library': libraryName});
  856. initializers[libraryType][libraryName] = initializers[libraryType][0];
  857. }
  858. initializers[libraryType][libraryName].active = true;
  859. if (userLibraries[libraryType][libraryName] && userLibraries[libraryType][libraryName] != "") {
  860. if (typeof initializers[libraryType][libraryName].parameters == "object") {
  861. initializers[libraryType][libraryName].parameters = Object.assign({}, initializers[libraryType][libraryName].parameters, userLibraries[libraryType][libraryName]);
  862. } else {
  863. initializers[libraryType][libraryName].parameters = userLibraries[libraryType][libraryName];
  864. }
  865. }
  866. });
  867. }
  868. })
  869. // Load default renderer if no other librarys specified
  870. // if (Object.keys(userLibraries["model"]).length == 0 && Object.keys(userLibraries["view"]).length == 0) {
  871. // // requireArray["vwf/model/threejs"].active = true;
  872. // }
  873. // With the scripts loaded, we must initialize the framework. vwf.initialize()
  874. // accepts three parameters: a world specification, model configuration parameters,
  875. // and view configuration parameters.
  876. self.initialize(self.applicationLoad, getActiveLibraries(initializers["model"], true), getActiveLibraries(initializers["view"], true), callback);
  877. }
  878. // -- initialize ---------------------------------------------------------------------------
  879. /// The main page only needs to call vwf.initialize() to launch the application. Use
  880. /// require.ready() or jQuery(document).ready() to call initialize() once the page has
  881. /// loaded. initialize() accepts three parameters.
  882. ///
  883. /// A component specification identifies the application to be loaded. If a URI is provided,
  884. /// the specification is loaded from there [1]. Alternately, a JavaScript object literal
  885. /// containing the specfication may be provided [2]. Since a component can extend and
  886. /// specialize a prototype, using a simple object literal allows existing component to be
  887. /// configured for special uses [3].
  888. ///
  889. /// [1] vwf.initialize( "http://vwf.example.com/applications/sample12345", ... )
  890. ///
  891. /// [2] vwf.initialize( { source: "model.dae", type: "model/vnd.collada+xml",
  892. /// properties: { "p1": ... }, ... }, ... )
  893. ///
  894. /// [3] vwf.initialize( { extends: "http://vwf.example.com/applications/sample12345",
  895. /// source: "alternate-model.dae", type: "model/vnd.collada+xml" }, ... )
  896. ///
  897. /// modelInitializers and viewInitializers identify the model and view modules that should be
  898. /// attached to the simulation. Each is specified as an array of objects that map the name of
  899. /// a model or view to construct to the set of arguments to pass to its constructor. Modules
  900. /// without parameters may be specified as a string [4]. Arguments may be specified as an
  901. /// array [5], or as a single value if there is only one [6].
  902. ///
  903. /// [4] vwf.initialize( ..., [ "vwf/model/javascript" ], [ ... ] )
  904. /// [5] vwf.initialize( ..., [ { "vwf/model/glge": [ "#scene, "second param" ] } ], [ ... ] )
  905. /// [6] vwf.initialize( ..., [ { "vwf/model/glge": "#scene" } ], [ ... ] )
  906. ///
  907. /// @name module:vwf.initialize
  908. async initialize(
  909. /* [ componentURI|componentObject ] [ modelInitializers ]
  910. [ viewInitializers ] */
  911. ) {
  912. let self = this;
  913. var args = Array.prototype.slice.call(arguments);
  914. //var application;
  915. // Load the runtime configuration. We start with the factory defaults. The reflector may
  916. // provide additional settings when we connect.
  917. //this.configuration = require("vwf/configuration").active; // "active" updates in place and changes don't invalidate the reference
  918. // Load the kernel utilities.
  919. //this.kutility = new KUtility //require("vwf/kernel/utility");
  920. // Create the logger.
  921. //this.logger = require("logger").for("vwf", this); // TODO: for( "vwf", ... ), and update existing calls
  922. // Get the jQuery reference. This also happens in `loadConfiguration`, but the tests
  923. // initialize using `initialize` and don't call `loadConfiguration` first.
  924. // jQuery = require("jquery");
  925. // Parse the function parameters. If the first parameter is not an array, then treat it
  926. // as the application specification. Otherwise, fall back to the "application" parameter
  927. // in the query string.
  928. if (typeof args[0] != "object" || !(args[0] instanceof Array)) {
  929. this.applicationLoad = args.shift();
  930. }
  931. // Shift off the parameter containing the model list and initializer arguments.
  932. var modelInitializers = args.shift() || [];
  933. // Shift off the parameter containing the view list and initializer arguments.
  934. var viewInitializers = args.shift() || [];
  935. var callback = args.shift();
  936. var compatibilityStatus = {
  937. compatible: true,
  938. errors: {}
  939. };
  940. // Create the model interface to the kernel. Models can make direct calls that execute
  941. // immediately or future calls that are placed on the queue and executed when removed.
  942. let modelKernel = new ModelKernel({
  943. id:"vwf/kernel/model"
  944. }).factory();
  945. this.models.kernel = modelKernel.create(vwf);
  946. //this.models.kernel = require("vwf/kernel/model").create(vwf);
  947. // Create and attach each configured model.
  948. for (let modelInitializer of modelInitializers) {
  949. //modelInitializers.forEach(function (modelInitializer) {
  950. // Skip falsy values to allow initializers to be conditionally included by the
  951. // loader.
  952. if (modelInitializer) {
  953. // Accept either { "vwf/model/name": [ arguments] } or "vwf/model/name".
  954. if (typeof modelInitializer == "object" && modelInitializer != null) {
  955. var modelName = Object.keys(modelInitializer)[0];
  956. var modelArguments = modelInitializer[modelName];
  957. } else {
  958. var modelName = modelInitializer;
  959. var modelArguments = undefined;
  960. }
  961. let log = new Log({
  962. id:"vwf/model/stage/log"
  963. }).factory();
  964. //
  965. var modelMod = undefined;
  966. await import(modelName+'.js').then(m=>{
  967. modelMod = (new m.default({
  968. id: modelName
  969. }).factory())
  970. });
  971. var model = modelMod.create(
  972. this.models.kernel, // model's kernel access
  973. [log],
  974. //[require("vwf/model/stage/log")], // stages between the kernel and model
  975. {}, // state shared with a paired view
  976. [].concat(modelArguments || []) // arguments for initialize()
  977. );
  978. if (model) {
  979. this.models.push(model);
  980. this.models[modelName] = model; // also index by id // TODO: this won't work if multiple model instances are allowed
  981. if (modelName == "/core/vwf/model/javascript") { // TODO: need a formal way to follow prototype chain from vwf.js; this is peeking inside of vwf-model-javascript
  982. this.models.javascript = model;
  983. while (this.models.javascript.model) this.models.javascript = this.models.javascript.model;
  984. }
  985. if (modelName == "/core/vwf/model/object") { // TODO: this is peeking inside of vwf-model-object
  986. this.models.object = model;
  987. while (this.models.object.model) this.models.object = this.models.object.model;
  988. }
  989. if (model.model.compatibilityStatus) {
  990. if (!model.model.compatibilityStatus.compatible) {
  991. compatibilityStatus.compatible = false;
  992. Object.assign(compatibilityStatus.errors, model.model.compatibilityStatus.errors);
  993. //jQuery.extend(compatibilityStatus.errors, model.model.compatibilityStatus.errors);
  994. }
  995. }
  996. }
  997. }
  998. }
  999. //, this);
  1000. // Create the view interface to the kernel. Views can only make replicated calls which
  1001. // bounce off the reflection server, are placed on the queue when received, and executed
  1002. // when removed.
  1003. let viewKernel = new ViewKernel({
  1004. id:"vwf/kernel/view"
  1005. }).factory();
  1006. this.views.kernel = viewKernel.create(vwf);
  1007. //this.views.kernel = require("vwf/kernel/view").create(vwf);
  1008. // Create and attach each configured view.
  1009. for( let viewInitializer of viewInitializers) {
  1010. //viewInitializers.forEach(function (viewInitializer) {
  1011. // Skip falsy values to allow initializers to be conditionally included by the
  1012. // loader.
  1013. if (viewInitializer) {
  1014. // Accept either { "vwf/view/name": [ arguments] } or "vwf/view/name".
  1015. if (typeof viewInitializer == "object" && viewInitializer != null) {
  1016. var viewName = Object.keys(viewInitializer)[0];
  1017. var viewArguments = viewInitializer[viewName];
  1018. } else {
  1019. var viewName = viewInitializer;
  1020. var viewArguments = undefined;
  1021. }
  1022. // if (!viewName.match("^vwf/view/")) { // old way
  1023. // var view = this.modules[viewName];
  1024. // if (view) {
  1025. // var instance = new view();
  1026. // instance.state = this.models.actual["vwf/model/" + viewName] && this.models.actual["vwf/model/" + viewName].state || {}; // state shared with a paired model
  1027. // view.apply(instance, [vwf].concat(viewArguments || []));
  1028. // this.views.push(instance);
  1029. // this.views[viewName] = instance; // also index by id // TODO: this won't work if multiple view instances are allowed
  1030. // if (view.compatibilityStatus) {
  1031. // if (!view.compatibilityStatus.compatible) {
  1032. // compatibilityStatus.compatible = false;
  1033. // Object.assign(compatibilityStatus.errors, view.compatibilityStatus.errors);
  1034. // // jQuery.extend(compatibilityStatus.errors, view.compatibilityStatus.errors);
  1035. // }
  1036. // }
  1037. // }
  1038. // } else {
  1039. // new way
  1040. var modelPeer = this.models.actual[viewName.replace("view/", "model/")]; // TODO: this.model.actual() is kind of heavy, but it's probably OK to use just a few times here at start-up
  1041. var viewMod = undefined;
  1042. await import(viewName +'.js').then(m=>{
  1043. viewMod = (new m.default({
  1044. id: viewName
  1045. }).factory())
  1046. })
  1047. var view = viewMod.create(
  1048. this.views.kernel, // view's kernel access
  1049. [], // stages between the kernel and view
  1050. modelPeer && modelPeer.state || {}, // state shared with a paired model
  1051. [].concat(viewArguments || []) // arguments for initialize()
  1052. );
  1053. if (view) {
  1054. this.views.push(view);
  1055. this.views[viewName] = view; // also index by id // TODO: this won't work if multiple view instances are allowed
  1056. if (view.compatibilityStatus) {
  1057. if (!view.compatibilityStatus.compatible) {
  1058. compatibilityStatus.compatible = false;
  1059. Object.assign(compatibilityStatus.errors, view.compatibilityStatus.errors);
  1060. // jQuery.extend(compatibilityStatus.errors, view.compatibilityStatus.errors);
  1061. }
  1062. }
  1063. }
  1064. //}
  1065. }
  1066. }
  1067. //, this);
  1068. if (callback) {
  1069. callback(compatibilityStatus);
  1070. }
  1071. //await _app.getApplicationState();
  1072. await _app.getApplicationState()
  1073. .then(res => {
  1074. return self.chooseConnection(res)
  1075. })
  1076. .then(res => {
  1077. self.ready(self.application, res)
  1078. })
  1079. }
  1080. // -- ready --------------------------------------------------------------------------------
  1081. /// @name module:vwf.ready
  1082. ready(component_uri_or_json_or_object, path) {
  1083. // Connect to the reflector. This implementation uses the socket.io library, which
  1084. // communicates using a channel back to the server that provided the client documents.
  1085. if (this.isLuminary) {
  1086. //Use Luminary for connection
  1087. this.namespace_ = this.luminary.namespace; //this.helpers.GetNamespace(path.path); //.split(".").join("_");
  1088. this.moniker_ = this.luminary.clientID;
  1089. console.log('namespace: ' + this.namespace_, ' for client: ' + this.moniker_);
  1090. //let heartbeat = _LCSDB.get('server').get('heartbeat');
  1091. var heartbeat = _lum.get(this.namespace_).get('heartbeat'); //_LCSDB.get(vwf.namespace_).get('heartbeat');
  1092. if (this.isLuminaryGlobalHB && this.luminaryGlobalHBPath) {
  1093. let hbPath = this.luminaryGlobalHBPath.split('/');
  1094. var heartbeat = _LCSDB;
  1095. hbPath.forEach(el => {
  1096. heartbeat = heartbeat.get(el);
  1097. })
  1098. }
  1099. this.luminary.subscribeOnHeartbeat(heartbeat);
  1100. this.luminary.subscribeOnMessages();
  1101. } else {
  1102. //Use Reflector for connection
  1103. this.reflectorClient.connect(component_uri_or_json_or_object, path);
  1104. }
  1105. }
  1106. // -- log ----------------------------------------------------------------------------------
  1107. /// Send a log message to the reflector.
  1108. ///
  1109. /// @name module:vwf.log
  1110. log() {
  1111. this.respond(undefined, "log", undefined, undefined, arguments);
  1112. }
  1113. // -- setState -----------------------------------------------------------------------------
  1114. /// setState may complete asynchronously due to its dependence on createNode. To prevent
  1115. /// actions from executing out of order, queue processing must be suspended while setState is
  1116. /// in progress. createNode suspends the queue when necessary, but additional calls to
  1117. /// suspend and resume the queue may be needed if other async operations are added.
  1118. ///
  1119. /// @name module:vwf.setState
  1120. ///
  1121. /// @see {@link module:vwf/api/kernel.setState}
  1122. setState(appState, callback_async /* () */ ) {
  1123. let self = this;
  1124. this.logger.debuggx("setState"); // TODO: loggableState
  1125. // Set the runtime configuration.
  1126. var applicationState = appState;
  1127. if (applicationState.init) {
  1128. applicationState = JSON.parse(localStorage.getItem('lcs_app')).saveObject
  1129. }
  1130. if (applicationState.configuration) {
  1131. this.configuration = applicationState.configuration;
  1132. //require("vwf/configuration").instance = applicationState.configuration;
  1133. }
  1134. // Update the internal kernel state.
  1135. if (applicationState.kernel) {
  1136. if (applicationState.kernel.time !== undefined) self.virtualTime.now = applicationState.kernel.time;
  1137. }
  1138. // Create or update global nodes and their descendants.
  1139. var nodes = applicationState.nodes || [];
  1140. var annotations = applicationState.annotations || {};
  1141. var nodeIndex = 0;
  1142. async.forEachSeries(nodes, function (nodeComponent, each_callback_async /* ( err ) */ ) {
  1143. // Look up a possible annotation for this node. For backward compatibility, if the
  1144. // state has exactly one node and doesn't contain an annotations object, assume the
  1145. // node is the application.
  1146. var nodeAnnotation = self.nodes.length > 1 || applicationState.annotations ?
  1147. annotations[nodeIndex] : "application";
  1148. self.createNode(nodeComponent, nodeAnnotation, function (nodeID) /* async */ {
  1149. each_callback_async(undefined);
  1150. });
  1151. nodeIndex++;
  1152. }, function (err) /* async */ {
  1153. // Clear the message queue, except for reflector messages that arrived after the
  1154. // current action.
  1155. self.virtualTime.filterQueue();
  1156. // Set the queue time and add the incoming items to the queue.
  1157. if (applicationState.queue) {
  1158. self.virtualTime.time = applicationState.queue.time;
  1159. self.virtualTime.insert(applicationState.queue.queue || []);
  1160. }
  1161. callback_async && callback_async();
  1162. });
  1163. this.logger.debugu();
  1164. };
  1165. // -- getState -----------------------------------------------------------------------------
  1166. /// @name module:vwf.getState
  1167. ///
  1168. /// @see {@link module:vwf/api/kernel.getState}
  1169. getState(full, normalize) {
  1170. let self = this;
  1171. this.logger.debuggx("getState", full, normalize);
  1172. // Get the application nodes and queue.
  1173. var applicationState = {
  1174. // Runtime configuration.
  1175. configuration: self.configuration, //require("vwf/configuration").active,
  1176. // Internal kernel state.
  1177. kernel: {
  1178. time: self.virtualTime.now,
  1179. },
  1180. // Global node and descendant deltas.
  1181. nodes: [ // TODO: all global objects
  1182. this.getNode("proxy/clients.vwf", full),
  1183. this.getNode(this.application(), full),
  1184. ],
  1185. // `createNode` annotations, keyed by `nodes` indexes.
  1186. annotations: {
  1187. 1: "application",
  1188. },
  1189. // Message queue.
  1190. queue: self.virtualTime.stateQueue
  1191. };
  1192. // Normalize for consistency.
  1193. if (normalize) {
  1194. applicationState = self.utility.transform(
  1195. applicationState, self.utility.transforms.hash);
  1196. }
  1197. this.logger.debugu();
  1198. return applicationState;
  1199. };
  1200. // -- hashState ----------------------------------------------------------------------------
  1201. /// @name module:vwf.hashState
  1202. ///
  1203. /// @see {@link module:vwf/api/kernel.hashState}
  1204. hashState() {
  1205. this.logger.debuggx("hashState");
  1206. var applicationState = this.getState(true, true);
  1207. // Hash the nodes.
  1208. var hashn = this.hashNode(applicationState.nodes[0]); // TODO: all global objects
  1209. // Hash the queue.
  1210. var hashq = "q" + Crypto.MD5(JSON.stringify(applicationState.queue)).toString().substring(0, 16);
  1211. // Hash the other kernel properties.
  1212. var hashk = "k" + Crypto.MD5(JSON.stringify(applicationState.kernel)).toString().substring(0, 16);
  1213. this.logger.debugu();
  1214. // Generate the combined hash.
  1215. return hashn + ":" + hashq + ":" + hashk;
  1216. }
  1217. // -- createNode ---------------------------------------------------------------------------
  1218. /// Create a node from a component specification. Construction may require loading data from
  1219. /// multiple remote documents. This function returns before construction is complete. A
  1220. /// callback is invoked once the node has fully loaded.
  1221. ///
  1222. /// A simple node consists of a set of properties, methods and events, but a node may
  1223. /// specialize a prototype component and may also contain multiple child nodes, any of which
  1224. /// may specialize a prototype component and contain child nodes, etc. So components cover a
  1225. /// vast range of complexity. The application definition for the overall simulation is a
  1226. /// single component instance.
  1227. ///
  1228. /// A node is a component instance--a single, anonymous specialization of its component.
  1229. /// Nodes specialize components in the same way that any component may specialize a prototype
  1230. /// component. The prototype component is made available as a base, then new or modified
  1231. /// properties, methods, events, child nodes and scripts are attached to modify the base
  1232. /// implemenation.
  1233. ///
  1234. /// To create a node, we first make the prototoype available by loading it (if it has not
  1235. /// already been loaded). This is a recursive call to createNode() with the prototype
  1236. /// specification. Then we add new, and modify existing, properties, methods, and events
  1237. /// according to the component specification. Then we load and add any children, again
  1238. /// recursively calling createNode() for each. Finally, we attach any new scripts and invoke
  1239. /// an initialization function.
  1240. ///
  1241. /// createNode may complete asynchronously due to its dependence on setNode, createChild and
  1242. /// loadComponent. To prevent actions from executing out of order, queue processing must be
  1243. /// suspended while createNode is in progress. setNode, createChild and loadComponent suspend
  1244. /// the queue when necessary, but additional calls to suspend and resume the queue may be
  1245. /// needed if other async operations are added.
  1246. ///
  1247. /// @name module:vwf.createNode
  1248. ///
  1249. /// @see {@link module:vwf/api/kernel.createNode}
  1250. createNode (nodeComponent, nodeAnnotation, baseURI, callback_async /* ( nodeID ) */ ) {
  1251. let self = this;
  1252. // Interpret `createNode( nodeComponent, callback )` as
  1253. // `createNode( nodeComponent, undefined, undefined, callback )` and
  1254. // `createNode( nodeComponent, nodeAnnotation, callback )` as
  1255. // `createNode( nodeComponent, nodeAnnotation, undefined, callback )`. `nodeAnnotation`
  1256. // was added in 0.6.12, and `baseURI` was added in 0.6.25.
  1257. if (typeof nodeAnnotation == "function" || nodeAnnotation instanceof Function) {
  1258. callback_async = nodeAnnotation;
  1259. baseURI = undefined;
  1260. nodeAnnotation = undefined;
  1261. } else if (typeof baseURI == "function" || baseURI instanceof Function) {
  1262. callback_async = baseURI;
  1263. baseURI = undefined;
  1264. }
  1265. this.logger.debuggx("createNode", function () {
  1266. return [JSON.stringify(self.loggableComponent(nodeComponent)), nodeAnnotation];
  1267. });
  1268. var nodePatch;
  1269. if (self.componentIsDescriptor(nodeComponent) && nodeComponent.patches) {
  1270. nodePatch = nodeComponent;
  1271. nodeComponent = nodeComponent.patches; // TODO: possible sync errors if the patched node is a URI component and the kernel state (time, random) is different from when the node was created on the originating client
  1272. }
  1273. // nodeComponent may be a URI, a descriptor, or an ID. While being created, it will
  1274. // transform from a URI to a descriptor to an ID (depending on its starting state).
  1275. // nodeURI, nodeDescriptor, and nodeID capture the intermediate states.
  1276. var nodeURI, nodeDescriptor, nodeID;
  1277. async.series([
  1278. // If `nodeComponent` is a URI, load the descriptor. `nodeComponent` may be a URI, a
  1279. // descriptor or an ID here.
  1280. function (series_callback_async /* ( err, results ) */ ) {
  1281. if (self.componentIsURI(nodeComponent)) { // URI // TODO: allow non-vwf URIs (models, images, etc.) to pass through to stage 2 and pass directly to createChild()
  1282. // Resolve relative URIs, but leave host-relative, locally-absolute
  1283. // references intact.
  1284. nodeURI = nodeComponent
  1285. //nodeComponent[0] == "/" ? nodeComponent : require( "vwf/utility" ).resolveURI( nodeComponent, baseURI );
  1286. // Load the document if we haven't seen this URI yet. Mark the components
  1287. // list to indicate that this component is loading.
  1288. if (!self.components[nodeURI]) { // uri is not loading (Array) or is loaded (id)
  1289. self.components[nodeURI] = []; // [] => array of callbacks while loading => true
  1290. self.loadComponent(nodeURI, undefined, function (nodeDescriptor) /* async */ {
  1291. nodeComponent = nodeDescriptor;
  1292. series_callback_async(undefined, undefined);
  1293. }, function (errorMessage) {
  1294. nodeComponent = undefined;
  1295. series_callback_async(errorMessage, undefined);
  1296. });
  1297. // If we've seen this URI, but it is still loading, just add our callback to
  1298. // the list. The original load's completion will call our callback too.
  1299. } else if (self.components[nodeURI] instanceof Array) { // uri is loading
  1300. callback_async && self.components[nodeURI].push(callback_async); // TODO: is this leaving a series callback hanging if we don't call series_callback_async?
  1301. // If this URI has already loaded, skip to the end and call the callback
  1302. // with the ID.
  1303. } else { // uri is loaded
  1304. if (nodePatch) {
  1305. self.setNode(self.components[nodeURI], nodePatch, function (nodeID) /* async */ {
  1306. callback_async && callback_async(self.components[nodeURI]); // TODO: is this leaving a series callback hanging if we don't call series_callback_async?
  1307. });
  1308. } else {
  1309. callback_async && callback_async(self.components[nodeURI]); // TODO: is this leaving a series callback hanging if we don't call series_callback_async?
  1310. }
  1311. }
  1312. } else { // descriptor, ID or error
  1313. series_callback_async(undefined, undefined);
  1314. }
  1315. },
  1316. // Rudimentary support for `{ includes: prototype }`, which absorbs a prototype
  1317. // descriptor into the node descriptor before creating the node.
  1318. // Notes:
  1319. //
  1320. // - Only supports one level, so `{ includes: prototype }` won't work if the
  1321. // prototype also contains a `includes` directive).
  1322. // - Only works with prototype URIs, so `{ includes: { ... descriptor ... } }`
  1323. // won't work.
  1324. // - Loads the prototype on each reference, so unlike real prototypes, multiple
  1325. // references to the same prototype cause multiple network loads.
  1326. //
  1327. // Also see the `mergeDescriptors` limitations.
  1328. function (series_callback_async /* ( err, results ) */ ) {
  1329. if (self.componentIsDescriptor(nodeComponent) && nodeComponent.includes && self.componentIsURI(nodeComponent.includes)) { // TODO: for "includes:", accept an already-loaded component (which componentIsURI exludes) since the descriptor will be loaded again
  1330. var prototypeURI = nodeComponent.includes //require( "vwf/utility" ).resolveURI( nodeComponent.includes, nodeURI || baseURI );
  1331. self.loadComponent(prototypeURI, undefined, function (prototypeDescriptor) /* async */ {
  1332. prototypeDescriptor = self.resolvedDescriptor(prototypeDescriptor, prototypeURI);
  1333. nodeComponent = self.mergeDescriptors(nodeComponent, prototypeDescriptor); // modifies prototypeDescriptor
  1334. series_callback_async(undefined, undefined);
  1335. }, function (errorMessage) {
  1336. nodeComponent = undefined;
  1337. series_callback_async(errorMessage, undefined);
  1338. });
  1339. } else {
  1340. series_callback_async(undefined, undefined);
  1341. }
  1342. },
  1343. // If `nodeComponent` is a descriptor, construct and get the ID. `nodeComponent` may
  1344. // be a descriptor or an ID here.
  1345. function (series_callback_async /* ( err, results ) */ ) {
  1346. if (self.componentIsDescriptor(nodeComponent)) { // descriptor // TODO: allow non-vwf URIs (models, images, etc.) to pass through to stage 2 and pass directly to createChild()
  1347. nodeDescriptor = nodeComponent;
  1348. // Create the node as an unnamed child global object.
  1349. self.createChild(0, nodeAnnotation, nodeDescriptor, nodeURI, function (nodeID) /* async */ {
  1350. nodeComponent = nodeID;
  1351. series_callback_async(undefined, undefined);
  1352. });
  1353. } else { // ID or error
  1354. series_callback_async(undefined, undefined);
  1355. }
  1356. },
  1357. // nodeComponent is an ID here.
  1358. function (series_callback_async /* ( err, results ) */ ) {
  1359. if (self.componentIsID(nodeComponent) || self.components[nodeComponent] instanceof Array) { // ID
  1360. nodeID = nodeComponent;
  1361. if (nodePatch) {
  1362. self.setNode(nodeID, nodePatch, function (nodeID) /* async */ {
  1363. series_callback_async(undefined, undefined);
  1364. });
  1365. } else {
  1366. series_callback_async(undefined, undefined);
  1367. }
  1368. } else { // error
  1369. series_callback_async(undefined, undefined); // TODO: error
  1370. }
  1371. },
  1372. ], function (err, results) /* async */ {
  1373. // If this node derived from a URI, save the list of callbacks waiting for
  1374. // completion and update the component list with the ID.
  1375. if (nodeURI) {
  1376. var callbacks_async = self.components[nodeURI];
  1377. self.components[nodeURI] = nodeID;
  1378. }
  1379. // Pass the ID to our callback.
  1380. callback_async && callback_async(nodeID); // TODO: handle error if invalid id
  1381. // Call the other callbacks.
  1382. if (nodeURI) {
  1383. callbacks_async.forEach(function (callback_async) {
  1384. callback_async && callback_async(nodeID);
  1385. });
  1386. }
  1387. });
  1388. this.logger.debugu();
  1389. }
  1390. // -- deleteNode ---------------------------------------------------------------------------
  1391. /// @name module:vwf.deleteNode
  1392. ///
  1393. /// @see {@link module:vwf/api/kernel.deleteNode}
  1394. deleteNode (nodeID) {
  1395. let self = this;
  1396. this.logger.debuggx("deleteNode", nodeID);
  1397. // Send the meta event into the application. We send it before deleting the child so
  1398. // that the child will still be available for review.
  1399. var parentID = this.parent(nodeID);
  1400. if (parentID !== 0) {
  1401. var nodeIndex = this.children(parentID).indexOf(nodeID);
  1402. if (nodeIndex < 0) {
  1403. nodeIndex = undefined;
  1404. }
  1405. if (this.models.kernel.enabled()) {
  1406. this.fireEvent(parentID, ["children", "removed"],
  1407. [nodeIndex, this.kutility.nodeReference(nodeID)]);
  1408. }
  1409. }
  1410. // Remove the entry in the components list if this was the root of a component loaded
  1411. // from a URI.
  1412. Object.keys(self.components).some(function (nodeURI) { // components: nodeURI => nodeID
  1413. if (self.components[nodeURI] == nodeID) {
  1414. delete self.components[nodeURI];
  1415. return true;
  1416. }
  1417. });
  1418. //Delete childs nodes
  1419. self.children(nodeID).forEach(function(child)
  1420. {
  1421. self.deleteNode(child);
  1422. });
  1423. // Call deletingNode() on each model. The node is considered deleted after all models
  1424. // have run.
  1425. this.models.forEach(function (model) {
  1426. model.deletingNode && model.deletingNode(nodeID);
  1427. });
  1428. // Unregister the node.
  1429. this.nodes.delete(nodeID, parentID);
  1430. // Call deletedNode() on each view. The view is being notified that a node has been
  1431. // deleted.
  1432. this.views.forEach(function (view) {
  1433. view.deletedNode && view.deletedNode(nodeID);
  1434. });
  1435. this.logger.debugu();
  1436. }
  1437. // -- setNode ------------------------------------------------------------------------------
  1438. /// setNode may complete asynchronously due to its dependence on createChild. To prevent
  1439. /// actions from executing out of order, queue processing must be suspended while setNode is
  1440. /// in progress. createChild suspends the queue when necessary, but additional calls to
  1441. /// suspend and resume the queue may be needed if other async operations are added.
  1442. ///
  1443. /// @name module:vwf.setNode
  1444. ///
  1445. /// @see {@link module:vwf/api/kernel.setNode}
  1446. setNode (nodeID, nodeComponent, callback_async /* ( nodeID ) */ ) { // TODO: merge with createChild?
  1447. let self = this;
  1448. self.logger.debuggx("setNode", function () {
  1449. return [nodeID, JSON.stringify(self.loggableComponent(nodeComponent))];
  1450. });
  1451. var node = self.nodes.existing[nodeID];
  1452. // Set the internal state.
  1453. self.models.object.internals(nodeID, nodeComponent);
  1454. // Suppress kernel reentry so that we can write the state without coloring from
  1455. // any scripts.
  1456. self.models.kernel.disable();
  1457. // Create the properties, methods, and events. For each item in each set, invoke
  1458. // createProperty(), createMethod(), or createEvent() to create the field. Each
  1459. // delegates to the models and views as above.
  1460. // Properties.
  1461. nodeComponent.properties && Object.keys(nodeComponent.properties).forEach(function (propertyName) { // TODO: setProperties should be adapted like this to be used here
  1462. var propertyValue = nodeComponent.properties[propertyName];
  1463. // Is the property specification directing us to create a new property, or
  1464. // initialize a property already defined on a prototype?
  1465. // Create a new property if the property is not defined on a prototype.
  1466. // Otherwise, initialize the property.
  1467. var creating = !node.properties.has(propertyName); // not defined on node or prototype
  1468. // Translate node references in the descriptor's form `{ node: nodeID }` into kernel
  1469. // node references.
  1470. if (self.valueHasAccessors(propertyValue) && propertyValue.node) {
  1471. propertyValue = self.kutility.nodeReference(propertyValue.node);
  1472. }
  1473. // Create or initialize the property.
  1474. if (creating) {
  1475. self.createProperty(nodeID, propertyName, propertyValue);
  1476. } else {
  1477. self.setProperty(nodeID, propertyName, propertyValue);
  1478. } // TODO: delete when propertyValue === null in patch
  1479. });
  1480. // Methods.
  1481. nodeComponent.methods && Object.keys(nodeComponent.methods).forEach(function (methodName) {
  1482. var methodHandler = nodeComponent.methods[methodName];
  1483. var creating = !node.methods.has(methodName); // not defined on node or prototype
  1484. // Create or initialize the method.
  1485. if (creating) {
  1486. self.createMethod(nodeID, methodName, methodHandler.parameters, methodHandler.body);
  1487. } else {
  1488. self.setMethod(nodeID, methodName, methodHandler);
  1489. } // TODO: delete when methodHandler === null in patch
  1490. });
  1491. // Events.
  1492. nodeComponent.events && Object.keys(nodeComponent.events).forEach(function (eventName) {
  1493. var eventDescriptor = nodeComponent.events[eventName];
  1494. var creating = !node.events.has(eventName); // not defined on node or prototype
  1495. // Create or initialize the event.
  1496. if (creating) {
  1497. self.createEvent(nodeID, eventName, eventDescriptor.parameters);
  1498. self.setEvent(nodeID, eventName, eventDescriptor); // set the listeners since `createEvent` can't do it yet
  1499. } else {
  1500. self.setEvent(nodeID, eventName, eventDescriptor);
  1501. } // TODO: delete when eventDescriptor === null in patch
  1502. });
  1503. // Restore kernel reentry.
  1504. self.models.kernel.enable();
  1505. async.series([
  1506. function (series_callback_async /* ( err, results ) */ ) {
  1507. // Create and attach the children. For each child, call createChild() with the
  1508. // child's component specification. createChild() delegates to the models and
  1509. // views as before.
  1510. async.forEach(Object.keys(nodeComponent.children || {}), function (childName, each_callback_async /* ( err ) */ ) {
  1511. var creating = !self.nodeHasOwnChild.call(self, nodeID, childName);
  1512. if (creating) {
  1513. self.createChild(nodeID, childName, nodeComponent.children[childName], undefined, function (childID) /* async */ { // TODO: add in original order from nodeComponent.children // TODO: ensure id matches nodeComponent.children[childName].id // TODO: propagate childURI + fragment identifier to children of a URI component?
  1514. each_callback_async(undefined);
  1515. });
  1516. } else {
  1517. self.setNode(nodeComponent.children[childName].id || nodeComponent.children[childName].patches,
  1518. nodeComponent.children[childName],
  1519. function (childID) /* async */ {
  1520. each_callback_async(undefined);
  1521. });
  1522. } // TODO: delete when nodeComponent.children[childName] === null in patch
  1523. }, function (err) /* async */ {
  1524. let deletedProtoNodes = nodeComponent.childrenDeleted;
  1525. if (deletedProtoNodes) {
  1526. let childNames = Object.keys(nodeComponent.childrenDeleted)
  1527. if (childNames) {
  1528. childNames.forEach(el => {
  1529. console.log("DELETE CHILD HERE!: ", el);
  1530. self.deleteChild(nodeID, el);
  1531. });
  1532. }
  1533. }
  1534. series_callback_async(err, undefined);
  1535. });
  1536. },
  1537. function (series_callback_async /* ( err, results ) */ ) {
  1538. // Attach the scripts. For each script, load the network resource if the script
  1539. // is specified as a URI, then once loaded, call execute() to direct any model
  1540. // that manages scripts of this script's type to evaluate the script where it
  1541. // will perform any immediate actions and retain any callbacks as appropriate
  1542. // for the script type.
  1543. var scripts = nodeComponent.scripts ? [].concat(nodeComponent.scripts) : []; // accept either an array or a single item
  1544. var baseURI = self.uri(nodeID, true);
  1545. async.map(scripts, function (script, map_callback_async /* ( err, result ) */ ) {
  1546. if (self.valueHasType(script)) {
  1547. if (script.source) {
  1548. self.loadScript(script.source, baseURI, function (scriptText) /* async */ { // TODO: this load would be better left to the driver, which may want to ignore it in certain cases, but that would require a completion callback from kernel.execute()
  1549. map_callback_async(undefined, {
  1550. text: scriptText,
  1551. type: script.type
  1552. });
  1553. }, function (errorMessage) {
  1554. map_callback_async(errorMessage, undefined);
  1555. });
  1556. } else {
  1557. map_callback_async(undefined, {
  1558. text: script.text,
  1559. type: script.type
  1560. });
  1561. }
  1562. } else {
  1563. map_callback_async(undefined, {
  1564. text: script,
  1565. type: undefined
  1566. });
  1567. }
  1568. }, function (err, scripts) /* async */ {
  1569. // Suppress kernel reentry so that initialization functions don't make any
  1570. // changes during replication.
  1571. self.models.kernel.disable();
  1572. // Create each script.
  1573. scripts.forEach(function (script) {
  1574. self.execute(nodeID, script.text, script.type); // TODO: callback
  1575. });
  1576. // Restore kernel reentry.
  1577. self.models.kernel.enable();
  1578. series_callback_async(err, undefined);
  1579. });
  1580. },
  1581. ], function (err, results) /* async */ {
  1582. callback_async && callback_async(nodeID);
  1583. });
  1584. this.logger.debugu();
  1585. return nodeComponent;
  1586. }
  1587. // -- getNode ------------------------------------------------------------------------------
  1588. /// @name module:vwf.getNode
  1589. ///
  1590. /// @see {@link module:vwf/api/kernel.getNode}
  1591. getNode(nodeID, full, normalize, proto) { // TODO: options to include/exclude children, prototypes
  1592. this.logger.debuggx("getNode", nodeID, full);
  1593. var node = this.nodes.existing[nodeID];
  1594. // Start the descriptor.
  1595. var nodeComponent = {};
  1596. // Arrange the component as a patch if the node originated in a URI component. We want
  1597. // to refer to the original URI but apply any changes that have been made to the node
  1598. // since it was loaded.
  1599. var patches = this.models.object.patches(nodeID),
  1600. patched = false;
  1601. if (node.patchable) {
  1602. nodeComponent.patches = node.uri || nodeID;
  1603. } else {
  1604. nodeComponent.id = nodeID;
  1605. }
  1606. // Intrinsic state. These don't change once created, so they can be omitted if we're
  1607. // patching.
  1608. if (full || !node.patchable) {
  1609. var intrinsics = this.intrinsics(nodeID); // source, type
  1610. var prototypeID = this.prototype(nodeID);
  1611. if (prototypeID === undefined) {
  1612. nodeComponent.extends = null;
  1613. } else if (prototypeID !== this.kutility.protoNodeURI) {
  1614. nodeComponent.extends = this.getNode(prototypeID); // TODO: move to vwf/model/object and get from intrinsics
  1615. }
  1616. nodeComponent.implements = this.behaviors(nodeID).map(function (behaviorID) {
  1617. return this.getNode(behaviorID); // TODO: move to vwf/model/object and get from intrinsics
  1618. }, this);
  1619. nodeComponent.implements.length || delete nodeComponent.implements;
  1620. if (intrinsics.source !== undefined) nodeComponent.source = intrinsics.source;
  1621. if (intrinsics.type !== undefined) nodeComponent.type = intrinsics.type;
  1622. }
  1623. // Internal state.
  1624. //patches = patches ? patches : {}
  1625. if (full || !node.patchable || patches.internals) {
  1626. var internals = this.models.object.internals(nodeID); // sequence and random
  1627. nodeComponent.sequence = internals.sequence;
  1628. nodeComponent.random = internals.random;
  1629. }
  1630. // Suppress kernel reentry so that we can read the state without coloring from any
  1631. // scripts.
  1632. this.models.kernel.disable();
  1633. // Properties.
  1634. if (full || !node.patchable) {
  1635. // Want everything, or only want patches but the node is not patchable.
  1636. nodeComponent.properties = this.getProperties(nodeID);
  1637. // Description of Getters & Setters
  1638. let jsProps = this.models.javascript.nodes[nodeID];
  1639. let getters = jsProps.private.getters;
  1640. let setters = jsProps.private.setters;
  1641. Object.keys(nodeComponent.properties).forEach(el => {
  1642. if (Object.keys(getters).includes(el) || Object.keys(setters).includes(el)) {
  1643. let prop = {
  1644. value: nodeComponent.properties[el]
  1645. }
  1646. if (typeof getters[el] == 'function') {
  1647. let fn = getters[el].toString()
  1648. prop.get = fn.slice(fn.indexOf("{") + 1, fn.lastIndexOf("}"));
  1649. } else {
  1650. prop.get = ""
  1651. }
  1652. if (typeof setters[el] == 'function') {
  1653. let fn = setters[el].toString()
  1654. prop.set = fn.slice(fn.indexOf("{") + 1, fn.lastIndexOf("}"));
  1655. } else {
  1656. prop.set = ""
  1657. }
  1658. nodeComponent.properties[el] = prop
  1659. }
  1660. })
  1661. ///end of Getters & Setters
  1662. for (var propertyName in nodeComponent.properties) {
  1663. var propertyValue = nodeComponent.properties[propertyName];
  1664. if (propertyValue === undefined) {
  1665. delete nodeComponent.properties[propertyName];
  1666. } else if (this.kutility.valueIsNodeReference(propertyValue)) {
  1667. // Translate kernel node references into descriptor node references.
  1668. nodeComponent.properties[propertyName] = {
  1669. node: propertyValue.id
  1670. };
  1671. }
  1672. }
  1673. } else if (node.properties.changes) {
  1674. // The node is patchable and properties have changed.
  1675. nodeComponent.properties = {};
  1676. Object.keys(node.properties.changes).forEach(function (propertyName) {
  1677. if (node.properties.changes[propertyName] !== "removed") { // TODO: handle delete
  1678. var propertyValue = this.getProperty(nodeID, propertyName);
  1679. if (this.kutility.valueIsNodeReference(propertyValue)) {
  1680. // Translate kernel node references into descriptor node references.
  1681. nodeComponent.properties[propertyName] = {
  1682. node: propertyValue.id
  1683. };
  1684. } else {
  1685. nodeComponent.properties[propertyName] = propertyValue;
  1686. }
  1687. }
  1688. }, this);
  1689. }
  1690. if (Object.keys(nodeComponent.properties).length == 0) {
  1691. delete nodeComponent.properties;
  1692. } else {
  1693. patched = true;
  1694. }
  1695. // Methods.
  1696. if (full || !node.patchable) {
  1697. Object.keys(node.methods.existing).forEach(function (methodName) {
  1698. nodeComponent.methods = nodeComponent.methods || {};
  1699. nodeComponent.methods[methodName] = this.getMethod(nodeID, methodName);
  1700. patched = true;
  1701. }, this);
  1702. } else if (node.methods.changes) {
  1703. Object.keys(node.methods.changes).forEach(function (methodName) {
  1704. if (node.methods.changes[methodName] !== "removed") { // TODO: handle delete
  1705. nodeComponent.methods = nodeComponent.methods || {};
  1706. nodeComponent.methods[methodName] = this.getMethod(nodeID, methodName);
  1707. patched = true;
  1708. }
  1709. }, this);
  1710. }
  1711. // Events.
  1712. var events = full || !node.patchable ?
  1713. node.events.existing : node.events.changes;
  1714. if (events) {
  1715. Object.keys(events).forEach(function (eventName) {
  1716. nodeComponent.events = nodeComponent.events || {};
  1717. nodeComponent.events[eventName] = this.getEvent(nodeID, eventName);
  1718. patched = true;
  1719. }, this);
  1720. }
  1721. // Restore kernel reentry.
  1722. this.models.kernel.enable();
  1723. // Children.
  1724. nodeComponent.children = {};
  1725. this.children(nodeID).forEach(function (childID) {
  1726. nodeComponent.children[this.name(childID)] = this.getNode(childID, full);
  1727. }, this);
  1728. for (var childName in nodeComponent.children) { // TODO: distinguish add, change, remove
  1729. if (nodeComponent.children[childName] === undefined) {
  1730. delete nodeComponent.children[childName];
  1731. }
  1732. }
  1733. ////CHECK FOR DELETED PROTO NODES
  1734. nodeComponent.childrenDeleted = {};
  1735. Object.keys(node.childsDeleted).forEach((childName) => {
  1736. nodeComponent.childrenDeleted[childName] = null;
  1737. patched = true;
  1738. });
  1739. ////
  1740. if (Object.keys(nodeComponent.children).length == 0) {
  1741. delete nodeComponent.children;
  1742. } else {
  1743. patched = true;
  1744. }
  1745. // Scripts.
  1746. // TODO: scripts
  1747. if (node.scripts) {
  1748. console.log("SCRIPTS: ", node.scripts)
  1749. }
  1750. // Normalize for consistency.
  1751. if (normalize) {
  1752. nodeComponent = self.utility.transform(
  1753. nodeComponent, self.utility.transforms.hash);
  1754. }
  1755. this.logger.debugu();
  1756. // Return the descriptor created, unless it was arranged as a patch and there were no
  1757. // changes. Otherwise, return the URI if this is the root of a URI component.
  1758. if (full || !node.patchable || patched) {
  1759. return nodeComponent;
  1760. } else if (node.uri) {
  1761. return node.uri;
  1762. } else {
  1763. return undefined;
  1764. }
  1765. };
  1766. // -- hashNode -----------------------------------------------------------------------------
  1767. /// @name module:vwf.hashNode
  1768. ///
  1769. /// @see {@link module:vwf/api/kernel.hashNode}
  1770. hashNode(nodeID) { // TODO: works with patches? // TODO: only for nodes from getNode( , , true )
  1771. this.logger.debuggx("hashNode", typeof nodeID == "object" ? nodeID.id : nodeID);
  1772. var nodeComponent = typeof nodeID == "object" ? nodeID : this.getNode(nodeID, true, true);
  1773. // Hash the intrinsic state.
  1774. var internal = {
  1775. id: nodeComponent.id,
  1776. source: nodeComponent.source,
  1777. type: nodeComponent.type
  1778. }; // TODO: get subset same way as getNode() puts them in without calling out specific field names
  1779. internal.source === undefined && delete internal.source;
  1780. internal.type === undefined && delete internal.type;
  1781. var hashi = "i" + Crypto.MD5(JSON.stringify(internal)).toString().substring(0, 16);
  1782. // Hash the properties.
  1783. var properties = nodeComponent.properties || {};
  1784. var hashp = Object.keys(properties).length ?
  1785. "p" + Crypto.MD5(JSON.stringify(properties)).toString().substring(0, 16) : undefined;
  1786. // Hash the children.
  1787. var children = nodeComponent.children || {};
  1788. var hashc = Object.keys(children).length ?
  1789. "c" + Crypto.MD5(JSON.stringify(children)).toString().substring(0, 16) : undefined;
  1790. this.logger.debugu();
  1791. // Generate the combined hash.
  1792. return hashi + (hashp ? "." + hashp : "") + (hashc ? "/" + hashc : "");
  1793. }
  1794. // -- createChild --------------------------------------------------------------------------
  1795. /// When we arrive here, we have a prototype node in hand (by way of its ID) and an object
  1796. /// containing a component specification. We now need to create and assemble the new node.
  1797. ///
  1798. /// The VWF manager doesn't directly manipulate any node. The various models act in
  1799. /// federation to create the greater model. The manager simply routes messages within the
  1800. /// system to allow the models to maintain the necessary data. Additionally, the views
  1801. /// receive similar messages that allow them to keep their interfaces current.
  1802. ///
  1803. /// To create a node, we simply assign a new ID, then invoke a notification on each model and
  1804. /// a notification on each view.
  1805. ///
  1806. /// createChild may complete asynchronously due to its dependence on createNode and the
  1807. /// creatingNode and createdNode driver calls. To prevent actions from executing out of
  1808. /// order, queue processing must be suspended while createChild is in progress. createNode
  1809. /// and the driver callbacks suspend the queue when necessary, but additional calls to
  1810. /// suspend and resume the queue may be needed if other async operations are added.
  1811. ///
  1812. /// @name module:vwf.createChild
  1813. ///
  1814. /// @see {@link module:vwf/api/kernel.createChild}
  1815. createChild(nodeID, childName, childComponent, childURI, callback_async /* ( childID ) */ ) {
  1816. let self = this;
  1817. this.logger.debuggx("createChild", function () {
  1818. return [nodeID, childName, JSON.stringify(self.loggableComponent(childComponent)), childURI];
  1819. });
  1820. childComponent = self.normalizedComponent(childComponent);
  1821. var child, childID, childIndex, childPrototypeID, childBehaviorIDs = [],
  1822. deferredInitializations = {};
  1823. var resolvedSource; // resolved `childComponent.source` for the drivers.
  1824. // Determine if we're replicating previously-saved state, or creating a fresh object.
  1825. var replicating = !!childComponent.id;
  1826. // Allocate an ID for the node. IDs must be unique and consistent across all clients
  1827. // sharing the same instance regardless of the component load order. Each node maintains
  1828. // a sequence counter, and we allocate the ID based on the parent's sequence counter and
  1829. // ID. Top-level nodes take the ID from their origin URI when available or from a hash
  1830. // of the descriptor. An existing ID is used when synchronizing to state drawn from
  1831. // another client or to a previously-saved state.
  1832. if (childComponent.id) { // incoming replication: pre-calculated id
  1833. childID = childComponent.id;
  1834. childIndex = this.children(nodeID).length;
  1835. } else if (nodeID === 0) { // global: component's URI or hash of its descriptor
  1836. childID = childURI ||
  1837. Crypto.MD5(JSON.stringify(childComponent)).toString(); // TODO: MD5 may be too slow here
  1838. childIndex = childURI;
  1839. } else { // descendant: parent id + next from parent's sequence
  1840. childID = nodeID + ":" + this.sequence(nodeID) +
  1841. (this.configuration["randomize-ids"] ? "-" + ("0" + Math.floor(this.random(nodeID) * 100)).slice(-2) : "") +
  1842. (this.configuration["humanize-ids"] ? "-" + childName.replace(/[^0-9A-Za-z_-]+/g, "-") : "");
  1843. childIndex = this.children(nodeID).length;
  1844. }
  1845. // Register the node.
  1846. child = self.nodes.create(childID, childPrototypeID, childBehaviorIDs, childURI, childName, nodeID);
  1847. // Register the node in vwf/model/object. Since the kernel delegates many node
  1848. // information functions to vwf/model/object, this serves to register it with the
  1849. // kernel. The node must be registered before any async operations occur to ensure that
  1850. // the parent's child list is correct when following siblings calculate their index
  1851. // numbers.
  1852. this.models.object.creatingNode(nodeID, childID, childPrototypeID, childBehaviorIDs,
  1853. childComponent.source, childComponent.type, childIndex, childName); // TODO: move node metadata back to the kernel and only use vwf/model/object just as a property store?
  1854. // The base URI for relative references is the URI of this node or the closest ancestor.
  1855. var baseURI = this.uri(childID, true);
  1856. // Construct the node.
  1857. async.series([
  1858. function (series_callback_async /* ( err, results ) */ ) {
  1859. // Rudimentary support for `{ includes: prototype }`, which absorbs a prototype
  1860. // descriptor into the child descriptor before creating the child. See the notes
  1861. // in `createNode` and the `mergeDescriptors` limitations.
  1862. // This first task always completes asynchronously (even if it doesn't perform
  1863. // an async operation) so that the stack doesn't grow from node to node while
  1864. // createChild() recursively traverses a component. If this task is moved,
  1865. // replace it with an async stub, or make the next task exclusively async.
  1866. if (self.componentIsDescriptor(childComponent) && childComponent.includes && self.componentIsURI(childComponent.includes)) { // TODO: for "includes:", accept an already-loaded component (which componentIsURI exludes) since the descriptor will be loaded again
  1867. var prototypeURI = childComponent.includes //require( "vwf/utility" ).resolveURI( childComponent.includes, baseURI );
  1868. var sync = true; // will loadComponent() complete synchronously?
  1869. self.loadComponent(prototypeURI, undefined, function (prototypeDescriptor) /* async */ {
  1870. // Resolve relative references with respect to the included component.
  1871. prototypeDescriptor = self.resolvedDescriptor(prototypeDescriptor, prototypeURI);
  1872. // Merge the child descriptor onto the `includes` descriptor.
  1873. childComponent = self.mergeDescriptors(childComponent, prototypeDescriptor); // modifies prototypeDescriptor
  1874. if (sync) {
  1875. self.virtualTime.suspend("before beginning " + childID); // suspend the queue
  1876. async.nextTick(function () {
  1877. series_callback_async(undefined, undefined);
  1878. self.virtualTime.resume("after beginning " + childID); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1879. });
  1880. } else {
  1881. series_callback_async(undefined, undefined);
  1882. }
  1883. }, function (errorMessage) {
  1884. childComponent = undefined;
  1885. series_callback_async(errorMessage, undefined);
  1886. });
  1887. sync = false; // not if we got here first
  1888. } else {
  1889. self.virtualTime.suspend("before beginning " + childID); // suspend the queue
  1890. async.nextTick(function () {
  1891. series_callback_async(undefined, undefined);
  1892. self.virtualTime.resume("after beginning " + childID); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1893. });
  1894. }
  1895. },
  1896. function (series_callback_async /* ( err, results ) */ ) {
  1897. // Create the prototype and behavior nodes (or locate previously created
  1898. // instances).
  1899. async.parallel([
  1900. function (parallel_callback_async /* ( err, results ) */ ) {
  1901. // Create or find the prototype and save the ID in childPrototypeID.
  1902. if (childComponent.extends !== null) { // TODO: any way to prevent node loading node as a prototype without having an explicit null prototype attribute in node?
  1903. var prototypeComponent = childComponent.extends || self.kutility.protoNodeURI;
  1904. self.createNode(prototypeComponent, undefined, baseURI, function (prototypeID) /* async */ {
  1905. childPrototypeID = prototypeID;
  1906. // TODO: the GLGE driver doesn't handle source/type or properties in prototypes properly; as a work-around pull those up into the component when not already defined
  1907. if (!childComponent.source) {
  1908. var prototype_intrinsics = self.intrinsics(prototypeID);
  1909. if (prototype_intrinsics.source) {
  1910. var prototype_uri = self.uri(prototypeID);
  1911. var prototype_properties = self.getProperties(prototypeID);
  1912. childComponent.source = prototype_intrinsics.source //require( "vwf/utility" ).resolveURI( prototype_intrinsics.source, prototype_uri );
  1913. childComponent.type = prototype_intrinsics.type;
  1914. childComponent.properties = childComponent.properties || {};
  1915. Object.keys(prototype_properties).forEach(function (prototype_property_name) {
  1916. if (childComponent.properties[prototype_property_name] === undefined && prototype_property_name != "transform") {
  1917. childComponent.properties[prototype_property_name] = prototype_properties[prototype_property_name];
  1918. }
  1919. });
  1920. }
  1921. }
  1922. parallel_callback_async(undefined, undefined);
  1923. });
  1924. } else {
  1925. childPrototypeID = undefined;
  1926. parallel_callback_async(undefined, undefined);
  1927. }
  1928. },
  1929. function (parallel_callback_async /* ( err, results ) */ ) {
  1930. // Create or find the behaviors and save the IDs in childBehaviorIDs.
  1931. var behaviorComponents = childComponent.implements ? [].concat(childComponent.implements) : []; // accept either an array or a single item
  1932. async.map(behaviorComponents, function (behaviorComponent, map_callback_async /* ( err, result ) */ ) {
  1933. self.createNode(behaviorComponent, undefined, baseURI, function (behaviorID) /* async */ {
  1934. map_callback_async(undefined, behaviorID);
  1935. });
  1936. }, function (err, behaviorIDs) /* async */ {
  1937. childBehaviorIDs = behaviorIDs;
  1938. parallel_callback_async(err, undefined);
  1939. });
  1940. },
  1941. ], function (err, results) /* async */ {
  1942. series_callback_async(err, undefined);
  1943. });
  1944. },
  1945. function (series_callback_async /* ( err, results ) */ ) {
  1946. // Re-register the node now that we have the prototypes and behaviors.
  1947. child = self.nodes.create(childID, childPrototypeID, childBehaviorIDs, childURI, childName, nodeID);
  1948. // For the proto-prototype node `node.vwf`, register the meta events.
  1949. if (childID === self.kutility.protoNodeURI) {
  1950. child.events.create(self.namespaceEncodedName(["properties", "created"]));
  1951. child.events.create(self.namespaceEncodedName(["properties", "initialized"]));
  1952. child.events.create(self.namespaceEncodedName(["properties", "deleted"]));
  1953. child.events.create(self.namespaceEncodedName(["methods", "created"]));
  1954. child.events.create(self.namespaceEncodedName(["methods", "deleted"]));
  1955. child.events.create(self.namespaceEncodedName(["events", "created"]));
  1956. child.events.create(self.namespaceEncodedName(["events", "deleted"]));
  1957. child.events.create(self.namespaceEncodedName(["children", "added"]));
  1958. child.events.create(self.namespaceEncodedName(["children", "removed"]));
  1959. }
  1960. // Re-register the node in vwf/model/object now that we have the prototypes and
  1961. // behaviors. vwf/model/object knows that we call it more than once and only
  1962. // updates the new information.
  1963. self.models.object.creatingNode(nodeID, childID, childPrototypeID, childBehaviorIDs,
  1964. childComponent.source, childComponent.type, childIndex, childName); // TODO: move node metadata back to the kernel and only use vwf/model/object just as a property store?
  1965. // Resolve the asset source URL for the drivers.
  1966. resolvedSource = childComponent.source && childComponent.source
  1967. //require( "vwf/utility" ).resolveURI( childComponent.source, baseURI );
  1968. // Call creatingNode() on each model. The node is considered to be constructed
  1969. // after all models have run.
  1970. async.forEachSeries(self.models, function (model, each_callback_async /* ( err ) */ ) {
  1971. var driver_ready = true;
  1972. var timeoutID;
  1973. // TODO: suppress kernel reentry here (just for childID?) with kernel/model showing a warning when breached; no actions are allowed until all drivers have seen creatingNode()
  1974. model.creatingNode && model.creatingNode(nodeID, childID, childPrototypeID, childBehaviorIDs,
  1975. resolvedSource, childComponent.type, childIndex, childName,
  1976. function (ready) /* async */ {
  1977. if (driver_ready && !ready) {
  1978. suspend();
  1979. } else if (!driver_ready && ready) {
  1980. resume();
  1981. }
  1982. function suspend() {
  1983. self.virtualTime.suspend("while loading " + childComponent.source + " for " + childID + " in creatingNode"); // suspend the queue
  1984. timeoutID = window.setTimeout(function () {
  1985. resume("timeout loading " + childComponent.source)
  1986. }, self.configuration["load-timeout"] * 1000);
  1987. driver_ready = false;
  1988. }
  1989. function resume(err) {
  1990. window.clearTimeout(timeoutID);
  1991. driver_ready = true;
  1992. err && self.logger.warnx("createChild", nodeID, childName + ":", err);
  1993. each_callback_async(err); // resume createChild()
  1994. self.virtualTime.resume("after loading " + childComponent.source + " for " + childID + " in creatingNode"); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1995. }
  1996. });
  1997. // TODO: restore kernel reentry here
  1998. driver_ready && each_callback_async(undefined);
  1999. }, function (err) /* async */ {
  2000. series_callback_async(err, undefined);
  2001. });
  2002. },
  2003. function (series_callback_async /* ( err, results ) */ ) {
  2004. // Call createdNode() on each view. The view is being notified of a node that has
  2005. // been constructed.
  2006. async.forEach(self.views, function (view, each_callback_async /* ( err ) */ ) {
  2007. var driver_ready = true;
  2008. var timeoutID;
  2009. view.createdNode && view.createdNode(nodeID, childID, childPrototypeID, childBehaviorIDs,
  2010. resolvedSource, childComponent.type, childIndex, childName,
  2011. function (ready) /* async */ {
  2012. if (driver_ready && !ready) {
  2013. suspend();
  2014. } else if (!driver_ready && ready) {
  2015. resume();
  2016. }
  2017. function suspend() {
  2018. self.virtualTime.suspend("while loading " + childComponent.source + " for " + childID + " in createdNode"); // suspend the queue
  2019. timeoutID = window.setTimeout(function () {
  2020. resume("timeout loading " + childComponent.source)
  2021. }, self.configuration["load-timeout"] * 1000);
  2022. driver_ready = false;
  2023. }
  2024. function resume(err) {
  2025. window.clearTimeout(timeoutID);
  2026. driver_ready = true;
  2027. err && self.logger.warnx("createChild", nodeID, childName + ":", err);
  2028. each_callback_async(err); // resume createChild()
  2029. self.virtualTime.resume("after loading " + childComponent.source + " for " + childID + " in createdNode"); // resume the queue; may invoke dispatch(), so call last before returning to the host
  2030. }
  2031. });
  2032. driver_ready && each_callback_async(undefined);
  2033. }, function (err) /* async */ {
  2034. series_callback_async(err, undefined);
  2035. });
  2036. },
  2037. function (series_callback_async /* ( err, results ) */ ) {
  2038. // Set the internal state.
  2039. self.models.object.internals(childID, childComponent);
  2040. // Suppress kernel reentry so that we can read the state without coloring from
  2041. // any scripts.
  2042. replicating && self.models.kernel.disable();
  2043. // Create the properties, methods, and events. For each item in each set, invoke
  2044. // createProperty(), createMethod(), or createEvent() to create the field. Each
  2045. // delegates to the models and views as above.
  2046. childComponent.properties && Object.keys(childComponent.properties).forEach(function (propertyName) {
  2047. var propertyValue = childComponent.properties[propertyName];
  2048. var value = propertyValue,
  2049. get, set, create;
  2050. if (self.valueHasAccessors(propertyValue)) {
  2051. value = propertyValue.node ? self.kutility.nodeReference(propertyValue.node) : propertyValue.value;
  2052. get = propertyValue.get;
  2053. set = propertyValue.set;
  2054. create = propertyValue.create;
  2055. }
  2056. // Is the property specification directing us to create a new property, or
  2057. // initialize a property already defined on a prototype?
  2058. // Create a new property if an explicit getter or setter are provided or if
  2059. // the property is not defined on a prototype. Initialize the property when
  2060. // the property is already defined on a prototype and no explicit getter or
  2061. // setter are provided.
  2062. var creating = create || // explicit create directive, or
  2063. get !== undefined || set !== undefined || // explicit accessor, or
  2064. !child.properties.has(propertyName); // not defined on prototype
  2065. // Are we assigning the value here, or deferring assignment until the node
  2066. // is constructed because setters will run?
  2067. var assigning = value === undefined || // no value, or
  2068. set === undefined && (creating || !self.nodePropertyHasSetter.call(self, childID, propertyName)) || // no setter, or
  2069. replicating; // replicating previously-saved state (setters never run during replication)
  2070. if (!assigning) {
  2071. deferredInitializations[propertyName] = value;
  2072. value = undefined;
  2073. }
  2074. // Create or initialize the property.
  2075. if (creating) {
  2076. self.createProperty(childID, propertyName, value, get, set);
  2077. } else {
  2078. self.setProperty(childID, propertyName, value);
  2079. }
  2080. });
  2081. childComponent.methods && Object.keys(childComponent.methods).forEach(function (methodName) {
  2082. var methodValue = childComponent.methods[methodName];
  2083. if (self.valueHasBody(methodValue)) {
  2084. self.createMethod(childID, methodName, methodValue.parameters, methodValue.body);
  2085. } else {
  2086. self.createMethod(childID, methodName, undefined, methodValue);
  2087. }
  2088. });
  2089. childComponent.events && Object.keys(childComponent.events).forEach(function (eventName) {
  2090. var eventValue = childComponent.events[eventName];
  2091. if (self.valueHasBody(eventValue)) {
  2092. self.createEvent(childID, eventName, eventValue.parameters);
  2093. self.setEvent(childID, eventName, eventValue); // set the listeners since `createEvent` can't do it yet
  2094. } else {
  2095. self.createEvent(childID, eventName, undefined);
  2096. }
  2097. });
  2098. // Restore kernel reentry.
  2099. replicating && self.models.kernel.enable();
  2100. // Create and attach the children. For each child, call createChild() with the
  2101. // child's component specification. createChild() delegates to the models and
  2102. // views as before.
  2103. async.forEach(Object.keys(childComponent.children || {}), function (childName, each_callback_async /* ( err ) */ ) {
  2104. var childValue = childComponent.children[childName];
  2105. self.createChild(childID, childName, childValue, undefined, function (childID) /* async */ { // TODO: add in original order from childComponent.children // TODO: propagate childURI + fragment identifier to children of a URI component?
  2106. each_callback_async(undefined);
  2107. });
  2108. }, function (err) /* async */ {
  2109. series_callback_async(err, undefined);
  2110. });
  2111. },
  2112. function (series_callback_async /* ( err, results ) */ ) {
  2113. // Attach the scripts. For each script, load the network resource if the script is
  2114. // specified as a URI, then once loaded, call execute() to direct any model that
  2115. // manages scripts of this script's type to evaluate the script where it will
  2116. // perform any immediate actions and retain any callbacks as appropriate for the
  2117. // script type.
  2118. var scripts = childComponent.scripts ? [].concat(childComponent.scripts) : []; // accept either an array or a single item
  2119. async.map(scripts, function (script, map_callback_async /* ( err, result ) */ ) {
  2120. if (self.valueHasType(script)) {
  2121. if (script.source) {
  2122. self.loadScript(script.source, baseURI, function (scriptText) /* async */ { // TODO: this load would be better left to the driver, which may want to ignore it in certain cases, but that would require a completion callback from kernel.execute()
  2123. map_callback_async(undefined, {
  2124. text: scriptText,
  2125. type: script.type
  2126. });
  2127. }, function (errorMessage) {
  2128. map_callback_async(errorMessage, undefined);
  2129. });
  2130. } else {
  2131. map_callback_async(undefined, {
  2132. text: script.text,
  2133. type: script.type
  2134. });
  2135. }
  2136. } else {
  2137. map_callback_async(undefined, {
  2138. text: script,
  2139. type: undefined
  2140. });
  2141. }
  2142. }, function (err, scripts) /* async */ {
  2143. // Watch for any async kernel calls generated as we run the scripts and wait
  2144. // for them complete before completing the node.
  2145. self.models.kernel.capturingAsyncs(function () {
  2146. // Suppress kernel reentry so that initialization functions don't make
  2147. // any changes during replication.
  2148. replicating && self.models.kernel.disable();
  2149. // Create each script.
  2150. scripts.forEach(function (script) {
  2151. self.execute(childID, script.text, script.type); // TODO: callback
  2152. });
  2153. // Perform initializations for properties with setter functions. These
  2154. // are assigned here so that the setters run on a fully-constructed node.
  2155. Object.keys(deferredInitializations).forEach(function (propertyName) {
  2156. self.setProperty(childID, propertyName, deferredInitializations[propertyName]);
  2157. });
  2158. // TODO: Adding the node to the tickable list here if it contains a tick() function in JavaScript at initialization time. Replace with better control of ticks on/off and the interval by the node.
  2159. if (self.execute(childID, "Boolean( this.tick )")) {
  2160. self.tickable.nodeIDs.push(childID);
  2161. }
  2162. // Restore kernel reentry.
  2163. replicating && self.models.kernel.enable();
  2164. }, function () {
  2165. // This function is called when all asynchronous calls from the previous
  2166. // function have returned.
  2167. // Call initializingNode() on each model and initializedNode() on each
  2168. // view to indicate that the node is fully constructed.
  2169. // Since nodes don't (currently) inherit their prototypes' children,
  2170. // for each prototype also call initializingNodeFromPrototype() to allow
  2171. // model drivers to apply the prototypes' initializers to the node.
  2172. async.forEachSeries(self.prototypes(childID, true).reverse().concat(childID),
  2173. function (childInitializingNodeID, each_callback_async /* err */ ) {
  2174. // Call initializingNode() on each model.
  2175. self.models.kernel.capturingAsyncs(function () {
  2176. self.models.forEach(function (model) {
  2177. // Suppress kernel reentry so that initialization functions
  2178. // don't make any changes during replication.
  2179. replicating && self.models.kernel.disable();
  2180. // For a prototype, call `initializingNodeFromPrototype` to
  2181. // run the prototype's initializer on the node. For the
  2182. // node, call `initializingNode` to run its own initializer.
  2183. //
  2184. // `initializingNodeFromPrototype` is separate from
  2185. // `initializingNode` so that `initializingNode` remains a
  2186. // single call that indicates that the node is fully
  2187. // constructed. Existing drivers, and any drivers that don't
  2188. // care about prototype initializers will by default ignore
  2189. // the intermediate initializations.
  2190. // (`initializingNodeFromPrototype` was added in 0.6.23.)
  2191. if (childInitializingNodeID !== childID) {
  2192. model.initializingNodeFromPrototype &&
  2193. model.initializingNodeFromPrototype(nodeID, childID, childInitializingNodeID);
  2194. } else {
  2195. model.initializingNode &&
  2196. model.initializingNode(nodeID, childID, childPrototypeID, childBehaviorIDs,
  2197. resolvedSource, childComponent.type, childIndex, childName);
  2198. }
  2199. // Restore kernel reentry.
  2200. replicating && self.models.kernel.enable();
  2201. });
  2202. }, function () {
  2203. each_callback_async(undefined);
  2204. });
  2205. },
  2206. function (err) /* async */ {
  2207. // Call initializedNode() on each view.
  2208. self.views.forEach(function (view) {
  2209. view.initializedNode && view.initializedNode(nodeID, childID, childPrototypeID, childBehaviorIDs,
  2210. resolvedSource, childComponent.type, childIndex, childName);
  2211. });
  2212. // Mark the node as initialized.
  2213. self.nodes.initialize(childID);
  2214. // Send the meta event into the application.
  2215. if (!replicating && nodeID !== 0) {
  2216. self.fireEvent(nodeID, ["children", "added"],
  2217. [childIndex, self.kutility.nodeReference(childID)]);
  2218. }
  2219. // Dismiss the loading spinner
  2220. if (childID === self.application()) {
  2221. _app.hideProgressBar();
  2222. }
  2223. series_callback_async(err, undefined);
  2224. });
  2225. });
  2226. });
  2227. },
  2228. ], function (err, results) /* async */ {
  2229. // The node is complete. Invoke the callback method and pass the new node ID and the
  2230. // ID of its prototype. If this was the root node for the application, the
  2231. // application is now fully initialized.
  2232. // Always complete asynchronously so that the stack doesn't grow from node to node
  2233. // while createChild() recursively traverses a component.
  2234. if (callback_async) {
  2235. self.virtualTime.suspend("before completing " + childID); // suspend the queue
  2236. async.nextTick(function () {
  2237. callback_async(childID);
  2238. self.virtualTime.resume("after completing " + childID); // resume the queue; may invoke dispatch(), so call last before returning to the host
  2239. });
  2240. }
  2241. });
  2242. this.logger.debugu();
  2243. }
  2244. // -- deleteChild --------------------------------------------------------------------------
  2245. /// @name module:vwf.deleteChild
  2246. ///
  2247. /// @see {@link module:vwf/api/kernel.deleteChild}
  2248. deleteChild(nodeID, childName) {
  2249. var childID = this.children(nodeID).filter(function (childID) {
  2250. return this.name(childID) === childName;
  2251. }, this)[0];
  2252. if (childID !== undefined) {
  2253. return this.deleteNode(childID);
  2254. }
  2255. }
  2256. // -- addChild -----------------------------------------------------------------------------
  2257. /// @name module:vwf.addChild
  2258. ///
  2259. /// @see {@link module:vwf/api/kernel.addChild}
  2260. addChild(nodeID, childID, childName) {
  2261. this.logger.debuggx("addChild", nodeID, childID, childName);
  2262. // Call addingChild() on each model. The child is considered added after all models have
  2263. // run.
  2264. this.models.forEach(function (model) {
  2265. model.addingChild && model.addingChild(nodeID, childID, childName);
  2266. });
  2267. // Call addedChild() on each view. The view is being notified that a child has been
  2268. // added.
  2269. this.views.forEach(function (view) {
  2270. view.addedChild && view.addedChild(nodeID, childID, childName);
  2271. });
  2272. this.logger.debugu();
  2273. }
  2274. // -- removeChild --------------------------------------------------------------------------
  2275. /// @name module:vwf.removeChild
  2276. ///
  2277. /// @see {@link module:vwf/api/kernel.removeChild}
  2278. removeChild(nodeID, childID) {
  2279. this.logger.debuggx("removeChild", nodeID, childID);
  2280. // Call removingChild() on each model. The child is considered removed after all models
  2281. // have run.
  2282. this.models.forEach(function (model) {
  2283. model.removingChild && model.removingChild(nodeID, childID);
  2284. });
  2285. // Call removedChild() on each view. The view is being notified that a child has been
  2286. // removed.
  2287. this.views.forEach(function (view) {
  2288. view.removedChild && view.removedChild(nodeID, childID);
  2289. });
  2290. this.logger.debugu();
  2291. }
  2292. // -- setProperties ------------------------------------------------------------------------
  2293. /// Set all of the properties for a node.
  2294. ///
  2295. /// @name module:vwf.setProperties
  2296. ///
  2297. /// @see {@link module:vwf/api/kernel.setProperties}
  2298. setProperties(nodeID, properties) { // TODO: rework as a cover for setProperty(), or remove; passing all properties to each driver is impractical since initializing and setting are different, and reentry can't be controlled when multiple sets are in progress.
  2299. let self = this;
  2300. this.logger.debuggx("setProperties", nodeID, properties);
  2301. var node = self.nodes.existing[nodeID];
  2302. var entrants = this.setProperty.entrants;
  2303. // Call settingProperties() on each model.
  2304. properties = this.models.reduceRight(function (intermediate_properties, model, index) { // TODO: note that we can't go left to right and stop after the first that accepts the set since we are setting all of the properties as a batch; verify that this creates the same result as calling setProperty individually on each property and that there are no side effects from setting through a driver after the one that handles the set.
  2305. var model_properties = {};
  2306. if (model.settingProperties) {
  2307. model_properties = model.settingProperties(nodeID, properties);
  2308. } else if (model.settingProperty) {
  2309. Object.keys(node.properties.existing).forEach(function (propertyName) {
  2310. if (properties[propertyName] !== undefined) {
  2311. var reentry = entrants[nodeID + '-' + propertyName] = {
  2312. index: index
  2313. }; // the active model number from this call // TODO: need unique nodeID+propertyName hash
  2314. model_properties[propertyName] =
  2315. model.settingProperty(nodeID, propertyName, properties[propertyName]);
  2316. if (self.models.kernel.blocked()) {
  2317. model_properties[propertyName] = undefined; // ignore result from a blocked setter
  2318. }
  2319. delete entrants[nodeID + '-' + propertyName];
  2320. }
  2321. });
  2322. }
  2323. Object.keys(node.properties.existing).forEach(function (propertyName) {
  2324. if (model_properties[propertyName] !== undefined) { // copy values from this model
  2325. intermediate_properties[propertyName] = model_properties[propertyName];
  2326. } else if (intermediate_properties[propertyName] === undefined) { // as well as recording any new keys
  2327. intermediate_properties[propertyName] = undefined;
  2328. }
  2329. });
  2330. return intermediate_properties;
  2331. }, {});
  2332. // Record the change.
  2333. if (node.initialized && node.patchable) {
  2334. Object.keys(properties).forEach(function (propertyName) {
  2335. node.properties.change(propertyName);
  2336. });
  2337. }
  2338. // Call satProperties() on each view.
  2339. this.views.forEach(function (view) {
  2340. if (view.satProperties) {
  2341. view.satProperties(nodeID, properties);
  2342. } else if (view.satProperty) {
  2343. for (var propertyName in properties) {
  2344. view.satProperty(nodeID, propertyName, properties[propertyName]); // TODO: be sure this is the value actually set, not the incoming value
  2345. }
  2346. }
  2347. });
  2348. this.logger.debugu();
  2349. return properties;
  2350. }
  2351. // -- getProperties ------------------------------------------------------------------------
  2352. /// Get all of the properties for a node.
  2353. ///
  2354. /// @name module:vwf.getProperties
  2355. ///
  2356. /// @see {@link module:vwf/api/kernel.getProperties}
  2357. getProperties(nodeID) { // TODO: rework as a cover for getProperty(), or remove; passing all properties to each driver is impractical since reentry can't be controlled when multiple gets are in progress.
  2358. let self = this;
  2359. this.logger.debuggx("getProperties", nodeID);
  2360. var node = self.nodes.existing[nodeID];
  2361. var entrants = this.getProperty.entrants;
  2362. // Call gettingProperties() on each model.
  2363. var properties = this.models.reduceRight(function (intermediate_properties, model, index) { // TODO: note that we can't go left to right and take the first result since we are getting all of the properties as a batch; verify that this creates the same result as calling getProperty individually on each property and that there are no side effects from getting through a driver after the one that handles the get.
  2364. var model_properties = {};
  2365. if (model.gettingProperties) {
  2366. model_properties = model.gettingProperties(nodeID, properties);
  2367. } else if (model.gettingProperty) {
  2368. Object.keys(node.properties.existing).forEach(function (propertyName) {
  2369. var reentry = entrants[nodeID + '-' + propertyName] = {
  2370. index: index
  2371. }; // the active model number from this call // TODO: need unique nodeID+propertyName hash
  2372. model_properties[propertyName] =
  2373. model.gettingProperty(nodeID, propertyName, intermediate_properties[propertyName]);
  2374. if (self.models.kernel.blocked()) {
  2375. model_properties[propertyName] = undefined; // ignore result from a blocked getter
  2376. }
  2377. delete entrants[nodeID + '-' + propertyName];
  2378. });
  2379. }
  2380. Object.keys(node.properties.existing).forEach(function (propertyName) {
  2381. if (model_properties[propertyName] !== undefined) { // copy values from this model
  2382. intermediate_properties[propertyName] = model_properties[propertyName];
  2383. } else if (intermediate_properties[propertyName] === undefined) { // as well as recording any new keys
  2384. intermediate_properties[propertyName] = undefined;
  2385. }
  2386. });
  2387. return intermediate_properties;
  2388. }, {});
  2389. // Call gotProperties() on each view.
  2390. this.views.forEach(function (view) {
  2391. if (view.gotProperties) {
  2392. view.gotProperties(nodeID, properties);
  2393. } else if (view.gotProperty) {
  2394. for (var propertyName in properties) {
  2395. view.gotProperty(nodeID, propertyName, properties[propertyName]); // TODO: be sure this is the value actually gotten and not an intermediate value from above
  2396. }
  2397. }
  2398. });
  2399. this.logger.debugu();
  2400. return properties;
  2401. }
  2402. // -- createProperty -----------------------------------------------------------------------
  2403. /// Create a property on a node and assign an initial value.
  2404. ///
  2405. /// @name module:vwf.createProperty
  2406. ///
  2407. /// @see {@link module:vwf/api/kernel.createProperty}
  2408. createProperty(nodeID, propertyName, propertyValue, propertyGet, propertySet) {
  2409. let self = this;
  2410. this.logger.debuggx("createProperty", function () {
  2411. return [nodeID, propertyName, JSON.stringify(self.loggableValue(propertyValue)),
  2412. self.loggableScript(propertyGet), self.loggableScript(propertySet)
  2413. ];
  2414. });
  2415. var node = self.nodes.existing[nodeID];
  2416. // Register the property.
  2417. node.properties.create(propertyName, node.initialized && node.patchable);
  2418. // Call creatingProperty() on each model. The property is considered created after all
  2419. // models have run.
  2420. this.models.forEach(function (model) {
  2421. model.creatingProperty && model.creatingProperty(nodeID, propertyName, propertyValue,
  2422. propertyGet, propertySet);
  2423. });
  2424. // Call createdProperty() on each view. The view is being notified that a property has
  2425. // been created.
  2426. this.views.forEach(function (view) {
  2427. view.createdProperty && view.createdProperty(nodeID, propertyName, propertyValue,
  2428. propertyGet, propertySet);
  2429. });
  2430. // Send the meta event into the application.
  2431. if (this.models.kernel.enabled()) {
  2432. this.fireEvent(nodeID, ["properties", "created"], [propertyName]);
  2433. }
  2434. this.logger.debugu();
  2435. return propertyValue;
  2436. }
  2437. // -- setProperty --------------------------------------------------------------------------
  2438. /// Set a property value on a node.
  2439. ///
  2440. /// @name module:vwf.setProperty
  2441. ///
  2442. /// @see {@link module:vwf/api/kernel.setProperty}
  2443. setProperty(nodeID, propertyName, propertyValue) {
  2444. let self = this;
  2445. this.logger.debuggx("setProperty", function () {
  2446. return [nodeID, propertyName, JSON.stringify(self.loggableValue(propertyValue))];
  2447. });
  2448. var node = self.nodes.existing[nodeID];
  2449. // Record calls into this function by nodeID and propertyName so that models may call
  2450. // back here (directly or indirectly) to delegate responses further down the chain
  2451. // without causing infinite recursion.
  2452. var entrants = this.setProperty.entrants;
  2453. var entry = entrants[nodeID + '-' + propertyName] || {}; // the most recent call, if any // TODO: need unique nodeID+propertyName hash
  2454. var reentry = entrants[nodeID + '-' + propertyName] = {}; // this call
  2455. // Select the actual driver calls. Create the property if it doesn't exist on this node
  2456. // or its prototypes. Initialize it if it exists on a prototype but not on this node.
  2457. // Set it if it already exists on this node.
  2458. if (!node.properties.has(propertyName) || entry.creating) {
  2459. reentry.creating = true;
  2460. var settingPropertyEtc = "creatingProperty";
  2461. var satPropertyEtc = "createdProperty";
  2462. node.properties.create(propertyName, node.initialized && node.patchable);
  2463. } else if (!node.properties.hasOwn(propertyName) || entry.initializing) {
  2464. reentry.initializing = true;
  2465. var settingPropertyEtc = "initializingProperty";
  2466. var satPropertyEtc = "initializedProperty";
  2467. node.properties.create(propertyName, node.initialized && node.patchable);
  2468. } else {
  2469. var settingPropertyEtc = "settingProperty";
  2470. var satPropertyEtc = "satProperty";
  2471. }
  2472. // Keep track of the number of assignments made by this `setProperty` call and others
  2473. // invoked indirectly by it, starting with the outermost call.
  2474. var outermost = entrants.assignments === undefined;
  2475. if (outermost) {
  2476. entrants.assignments = 0;
  2477. }
  2478. // Have we been called for the same property on the same node for a property still being
  2479. // assigned (such as when a setter function assigns the property to itself)? If so, then
  2480. // the inner call should skip drivers that the outer call has already invoked, and the
  2481. // outer call should complete without invoking drivers that the inner call will have
  2482. // already called.
  2483. var reentered = (entry.index !== undefined);
  2484. // We'll need to know if the set was delegated to other properties or actually assigned
  2485. // here.
  2486. var delegated = false,
  2487. assigned = false;
  2488. // Call settingProperty() on each model. The first model to return a non-undefined value
  2489. // has performed the set and dictates the return value. The property is considered set
  2490. // after all models have run.
  2491. this.models.some(function (model, index) {
  2492. // Skip initial models that an outer call has already invoked for this node and
  2493. // property (if any). If an inner call completed for this node and property, skip
  2494. // the remaining models.
  2495. if ((!reentered || index > entry.index) && !reentry.completed) {
  2496. // Record the active model number.
  2497. reentry.index = index;
  2498. // Record the number of assignments made since the outermost call. When
  2499. // `entrants.assignments` increases, a driver has called `setProperty` to make
  2500. // an assignment elsewhere.
  2501. var assignments = entrants.assignments;
  2502. // Make the call.
  2503. if (!delegated && !assigned) {
  2504. var value = model[settingPropertyEtc] && model[settingPropertyEtc](nodeID, propertyName, propertyValue);
  2505. } else {
  2506. model[settingPropertyEtc] && model[settingPropertyEtc](nodeID, propertyName, undefined);
  2507. }
  2508. // Ignore the result if reentry is disabled and the driver attempted to call
  2509. // back into the kernel. Kernel reentry is disabled during replication to
  2510. // prevent coloring from accessor scripts.
  2511. if (this.models.kernel.blocked()) { // TODO: this might be better handled wholly in vwf/kernel/model by converting to a stage and clearing blocked results on the return
  2512. value = undefined;
  2513. }
  2514. // The property was delegated if the call made any assignments.
  2515. if (entrants.assignments !== assignments) {
  2516. delegated = true;
  2517. }
  2518. // Otherwise if the call returned a value, the property was assigned here.
  2519. else if (value !== undefined) {
  2520. entrants.assignments++;
  2521. assigned = true;
  2522. }
  2523. // Record the value actually assigned. This may differ from the incoming value
  2524. // if it was range limited, quantized, etc. by the model. This is the value
  2525. // passed to the views.
  2526. if (value !== undefined) {
  2527. propertyValue = value;
  2528. }
  2529. // If we are setting, exit from the this.models.some() iterator once the value
  2530. // has been set. Don't exit early if we are creating or initializing since every
  2531. // model needs the opportunity to register the property.
  2532. return settingPropertyEtc == "settingProperty" && (delegated || assigned);
  2533. }
  2534. }, this);
  2535. // Record the change if the property was assigned here.
  2536. if (assigned && node.initialized && node.patchable) {
  2537. node.properties.change(propertyName);
  2538. }
  2539. // Call satProperty() on each view. The view is being notified that a property has
  2540. // been set. Only call for value properties as they are actually assigned. Don't call
  2541. // for accessor properties that have delegated to other properties. Notifying when
  2542. // setting an accessor property would be useful, but since that information is
  2543. // ephemeral, and views on late-joining clients would never see it, it's best to never
  2544. // send those notifications.
  2545. if (assigned) {
  2546. this.views.forEach(function (view) {
  2547. view[satPropertyEtc] && view[satPropertyEtc](nodeID, propertyName, propertyValue);
  2548. });
  2549. }
  2550. if (reentered) {
  2551. // For a reentrant call, restore the previous state and move the index forward to
  2552. // cover the models we called.
  2553. entrants[nodeID + '-' + propertyName] = entry;
  2554. entry.completed = true;
  2555. } else {
  2556. // Delete the call record if this is the first, non-reentrant call here (the normal
  2557. // case).
  2558. delete entrants[nodeID + '-' + propertyName];
  2559. // If the property was created or initialized, send the corresponding meta event
  2560. // into the application.
  2561. if (this.models.kernel.enabled()) {
  2562. if (settingPropertyEtc === "creatingProperty") {
  2563. this.fireEvent(nodeID, ["properties", "created"], [propertyName]);
  2564. } else if (settingPropertyEtc === "initializingProperty") {
  2565. this.fireEvent(nodeID, ["properties", "initialized"], [propertyName]);
  2566. }
  2567. }
  2568. }
  2569. // Clear the assignment counter when the outermost `setProperty` completes.
  2570. if (outermost) {
  2571. delete entrants.assignments;
  2572. }
  2573. this.logger.debugu();
  2574. return propertyValue;
  2575. }
  2576. // -- getProperty --------------------------------------------------------------------------
  2577. /// Get a property value for a node.
  2578. ///
  2579. /// @name module:vwf.getProperty
  2580. ///
  2581. /// @see {@link module:vwf/api/kernel.getProperty}
  2582. getProperty(nodeID, propertyName, ignorePrototype) {
  2583. this.logger.debuggx("getProperty", nodeID, propertyName);
  2584. var propertyValue = undefined;
  2585. // Record calls into this function by nodeID and propertyName so that models may call
  2586. // back here (directly or indirectly) to delegate responses further down the chain
  2587. // without causing infinite recursion.
  2588. var entrants = this.getProperty.entrants;
  2589. var entry = entrants[nodeID + '-' + propertyName] || {}; // the most recent call, if any // TODO: need unique nodeID+propertyName hash
  2590. var reentry = entrants[nodeID + '-' + propertyName] = {}; // this call
  2591. // Keep track of the number of retrievals made by this `getProperty` call and others
  2592. // invoked indirectly by it, starting with the outermost call.
  2593. var outermost = entrants.retrievals === undefined;
  2594. if (outermost) {
  2595. entrants.retrievals = 0;
  2596. }
  2597. // Have we been called for the same property on the same node for a property still being
  2598. // retrieved (such as when a getter function retrieves the property from itself)? If so,
  2599. // then the inner call should skip drivers that the outer call has already invoked, and
  2600. // the outer call should complete without invoking drivers that the inner call will have
  2601. // already called.
  2602. var reentered = (entry.index !== undefined);
  2603. // We'll need to know if the get was delegated to other properties or actually retrieved
  2604. // here.
  2605. var delegated = false,
  2606. retrieved = false;
  2607. // Call gettingProperty() on each model. The first model to return a non-undefined value
  2608. // dictates the return value.
  2609. this.models.some(function (model, index) {
  2610. // Skip initial models that an outer call has already invoked for this node and
  2611. // property (if any). If an inner call completed for this node and property, skip
  2612. // the remaining models.
  2613. if ((!reentered || index > entry.index) && !reentry.completed) {
  2614. // Record the active model number.
  2615. reentry.index = index;
  2616. // Record the number of retrievals made since the outermost call. When
  2617. // `entrants.retrievals` increases, a driver has called `getProperty` to make
  2618. // a retrieval elsewhere.
  2619. var retrievals = entrants.retrievals;
  2620. // Make the call.
  2621. var value = model.gettingProperty &&
  2622. model.gettingProperty(nodeID, propertyName, propertyValue); // TODO: probably don't need propertyValue here
  2623. // Ignore the result if reentry is disabled and the driver attempted to call
  2624. // back into the kernel. Kernel reentry is disabled during replication to
  2625. // prevent coloring from accessor scripts.
  2626. if (this.models.kernel.blocked()) { // TODO: this might be better handled wholly in vwf/kernel/model by converting to a stage and clearing blocked results on the return
  2627. value = undefined;
  2628. }
  2629. // The property was delegated if the call made any retrievals.
  2630. if (entrants.retrievals !== retrievals) {
  2631. delegated = true;
  2632. }
  2633. // Otherwise if the call returned a value, the property was retrieved here.
  2634. else if (value !== undefined) {
  2635. entrants.retrievals++;
  2636. retrieved = true;
  2637. }
  2638. // Record the value retrieved.
  2639. if (value !== undefined) {
  2640. propertyValue = value;
  2641. }
  2642. // Exit from the this.models.some() iterator once we have a return value.
  2643. return delegated || retrieved;
  2644. }
  2645. }, this);
  2646. if (reentered) {
  2647. // For a reentrant call, restore the previous state, move the index forward to cover
  2648. // the models we called.
  2649. entrants[nodeID + '-' + propertyName] = entry;
  2650. entry.completed = true;
  2651. } else {
  2652. // Delete the call record if this is the first, non-reentrant call here (the normal
  2653. // case).
  2654. delete entrants[nodeID + '-' + propertyName];
  2655. // Delegate to the behaviors and prototype if we didn't get a result from the
  2656. // current node.
  2657. if (propertyValue === undefined && !ignorePrototype) {
  2658. this.behaviors(nodeID).reverse().concat(this.prototype(nodeID)).
  2659. some(function (prototypeID, prototypeIndex, prototypeArray) {
  2660. if (prototypeIndex < prototypeArray.length - 1) {
  2661. propertyValue = this.getProperty(prototypeID, propertyName, true); // behavior node only, not its prototypes
  2662. } else if (prototypeID !== this.kutility.protoNodeURI) {
  2663. propertyValue = this.getProperty(prototypeID, propertyName); // prototype node, recursively
  2664. }
  2665. return propertyValue !== undefined;
  2666. }, this);
  2667. }
  2668. // Call gotProperty() on each view.
  2669. this.views.forEach(function (view) {
  2670. view.gotProperty && view.gotProperty(nodeID, propertyName, propertyValue); // TODO: be sure this is the value actually gotten and not an intermediate value from above
  2671. });
  2672. }
  2673. // Clear the retrieval counter when the outermost `getProperty` completes.
  2674. if (outermost) {
  2675. delete entrants.retrievals;
  2676. }
  2677. this.logger.debugu();
  2678. return propertyValue;
  2679. }
  2680. // -- createMethod -------------------------------------------------------------------------
  2681. /// @name module:vwf.createMethod
  2682. ///
  2683. /// @see {@link module:vwf/api/kernel.createMethod}
  2684. createMethod(nodeID, methodName, methodParameters, methodBody) {
  2685. let self = this;
  2686. this.logger.debuggx("createMethod", function () {
  2687. return [nodeID, methodName, methodParameters, self.loggableScript(methodBody)];
  2688. });
  2689. var node = self.nodes.existing[nodeID];
  2690. // Register the method.
  2691. node.methods.create(methodName, node.initialized && node.patchable);
  2692. // Call `creatingMethod` on each model. The method is considered created after all
  2693. // models have run.
  2694. this.models.forEach(function (model) {
  2695. model.creatingMethod && model.creatingMethod(nodeID, methodName, methodParameters,
  2696. methodBody);
  2697. });
  2698. // Call `createdMethod` on each view. The view is being notified that a method has been
  2699. // created.
  2700. this.views.forEach(function (view) {
  2701. view.createdMethod && view.createdMethod(nodeID, methodName, methodParameters,
  2702. methodBody);
  2703. });
  2704. // Send the meta event into the application.
  2705. if (this.models.kernel.enabled()) {
  2706. this.fireEvent(nodeID, ["methods", "created"], [methodName]);
  2707. }
  2708. this.logger.debugu();
  2709. }
  2710. // -- setMethod ----------------------------------------------------------------------------
  2711. /// @name module:vwf.setMethod
  2712. ///
  2713. /// @see {@link module:vwf/api/kernel.setMethod}
  2714. setMethod(nodeID, methodName, methodHandler) {
  2715. let self = this;
  2716. this.logger.debuggx("setMethod", function () {
  2717. return [nodeID, methodName]; // TODO loggable methodHandler
  2718. });
  2719. var node = this.nodes.existing[nodeID];
  2720. methodHandler = this.normalizedHandler(methodHandler);
  2721. if (!node.methods.hasOwn(methodName)) {
  2722. // If the method doesn't exist on this node, delegate to `kernel.createMethod` to
  2723. // create and assign the method.
  2724. this.createMethod(nodeID, methodName, methodHandler.parameters, methodHandler.body); // TODO: result
  2725. } else {
  2726. // Call `settingMethod` on each model. The first model to return a non-undefined
  2727. // value dictates the return value.
  2728. this.models.some(function (model) {
  2729. // Call the driver.
  2730. var handler = model.settingMethod && model.settingMethod(nodeID, methodName, methodHandler);
  2731. // Update the value to the value assigned if the driver handled it.
  2732. if (handler !== undefined) {
  2733. methodHandler = self.utility.merge({}, handler); // omit `undefined` values
  2734. }
  2735. // Exit the iterator once a driver has handled the assignment.
  2736. return handler !== undefined;
  2737. });
  2738. // Record the change.
  2739. if (node.initialized && node.patchable) {
  2740. node.methods.change(methodName);
  2741. }
  2742. // Call `satMethod` on each view.
  2743. this.views.forEach(function (view) {
  2744. view.satMethod && view.satMethod(nodeID, methodName, methodHandler);
  2745. });
  2746. }
  2747. this.logger.debugu();
  2748. return methodHandler;
  2749. }
  2750. // -- getMethod ----------------------------------------------------------------------------
  2751. /// @name module:vwf.getMethod
  2752. ///
  2753. /// @see {@link module:vwf/api/kernel.getMethod}
  2754. getMethod(nodeID, methodName) {
  2755. let self = this;
  2756. this.logger.debuggx("getMethod", function () {
  2757. return [nodeID, methodName];
  2758. });
  2759. var node = this.nodes.existing[nodeID];
  2760. // Call `gettingMethod` on each model. The first model to return a non-undefined value
  2761. // dictates the return value.
  2762. var methodHandler = {};
  2763. this.models.some(function (model) {
  2764. // Call the driver.
  2765. var handler = model.gettingMethod && model.gettingMethod(nodeID, methodName);
  2766. // Update the value to the value assigned if the driver handled it.
  2767. if (handler !== undefined) {
  2768. methodHandler = self.utility.merge({}, handler); // omit `undefined` values
  2769. }
  2770. // Exit the iterator once a driver has handled the retrieval.
  2771. return handler !== undefined;
  2772. });
  2773. // Call `gotMethod` on each view.
  2774. this.views.forEach(function (view) {
  2775. view.gotMethod && view.gotMethod(nodeID, methodName, methodHandler);
  2776. });
  2777. this.logger.debugu();
  2778. return methodHandler;
  2779. }
  2780. // -- callMethod ---------------------------------------------------------------------------
  2781. /// @name module:vwf.callMethod
  2782. ///
  2783. /// @see {@link module:vwf/api/kernel.callMethod}
  2784. callMethod(nodeID, methodName, methodParameters) {
  2785. let self = this;
  2786. this.logger.debuggx("callMethod", function () {
  2787. return [nodeID, methodName, JSON.stringify(self.loggableValues(methodParameters))];
  2788. });
  2789. // Call callingMethod() on each model. The first model to return a non-undefined value
  2790. // dictates the return value.
  2791. var methodValue = undefined;
  2792. this.models.some(function (model) {
  2793. methodValue = model.callingMethod && model.callingMethod(nodeID, methodName, methodParameters);
  2794. return methodValue !== undefined;
  2795. });
  2796. // Call calledMethod() on each view.
  2797. this.views.forEach(function (view) {
  2798. view.calledMethod && view.calledMethod(nodeID, methodName, methodParameters, methodValue);
  2799. });
  2800. this.logger.debugu();
  2801. return methodValue;
  2802. }
  2803. // -- createEvent --------------------------------------------------------------------------
  2804. /// @name module:vwf.createEvent
  2805. ///
  2806. /// @see {@link module:vwf/api/kernel.createEvent}
  2807. createEvent(nodeID, eventName, eventParameters) { // TODO: parameters (used? or just for annotation?) // TODO: allow a handler body here and treat as this.*event* = function() {} (a self-targeted handler); will help with ui event handlers
  2808. this.logger.debuggx("createEvent", nodeID, eventName, eventParameters);
  2809. var node = this.nodes.existing[nodeID];
  2810. // Encode any namespacing into the name. (Namespaced names were added in 0.6.21.)
  2811. var encodedEventName = this.namespaceEncodedName(eventName);
  2812. // Register the event.
  2813. node.events.create(encodedEventName, node.initialized && node.patchable, eventParameters);
  2814. // Call `creatingEvent` on each model. The event is considered created after all models
  2815. // have run.
  2816. this.models.forEach(function (model) {
  2817. model.creatingEvent && model.creatingEvent(nodeID, encodedEventName, eventParameters);
  2818. });
  2819. // Call `createdEvent` on each view. The view is being notified that a event has been
  2820. // created.
  2821. this.views.forEach(function (view) {
  2822. view.createdEvent && view.createdEvent(nodeID, encodedEventName, eventParameters);
  2823. });
  2824. // Send the meta event into the application.
  2825. if (this.models.kernel.enabled()) {
  2826. this.fireEvent(nodeID, ["events", "created"], [eventName]);
  2827. }
  2828. this.logger.debugu();
  2829. }
  2830. // -- setEvent -----------------------------------------------------------------------------
  2831. /// @name module:vwf.setEvent
  2832. ///
  2833. /// @see {@link module:vwf/api/kernel.setEvent}
  2834. setEvent(nodeID, eventName, eventDescriptor) {
  2835. this.logger.debuggx("setEvent", function () {
  2836. return [nodeID, eventName]; // TODO: loggable eventDescriptor
  2837. });
  2838. var node = this.nodes.existing[nodeID];
  2839. // eventDescriptor = normalizedHandler( eventDescriptor ); // TODO
  2840. // Encode any namespacing into the name.
  2841. var encodedEventName = this.namespaceEncodedName(eventName);
  2842. if (!node.events.hasOwn(encodedEventName)) {
  2843. // If the event doesn't exist on this node, delegate to `kernel.createEvent` to
  2844. // create and assign the event.
  2845. this.createEvent(nodeID, eventName, eventDescriptor.parameters); // TODO: result
  2846. (eventDescriptor.listeners || []).forEach(function (listener) {
  2847. return this.addEventListener(nodeID, eventName, listener, listener.context, listener.phases);
  2848. }, this);
  2849. } else {
  2850. // Locate the event in the registry.
  2851. var event = node.events.existing[encodedEventName];
  2852. // xxx
  2853. eventDescriptor = {
  2854. parameters: event.parameters ?
  2855. event.parameters.slice() : [], // TODO: note: we're ignoring eventDescriptor.parameters in the set
  2856. listeners: (eventDescriptor.listeners || []).map(function (listener) {
  2857. if (event.listeners.hasOwn(listener.id)) {
  2858. return this.setEventListener(nodeID, eventName, listener.id, listener);
  2859. } else {
  2860. return this.addEventListener(nodeID, eventName, listener, listener.context, listener.phases);
  2861. }
  2862. }, this),
  2863. };
  2864. }
  2865. this.logger.debugu();
  2866. return eventDescriptor;
  2867. }
  2868. // -- getEvent -----------------------------------------------------------------------------
  2869. /// @name module:vwf.getEvent
  2870. ///
  2871. /// @see {@link module:vwf/api/kernel.getEvent}
  2872. getEvent(nodeID, eventName) {
  2873. this.logger.debuggx("getEvent", function () {
  2874. return [nodeID, eventName];
  2875. });
  2876. var node = this.nodes.existing[nodeID];
  2877. // Encode any namespacing into the name.
  2878. var encodedEventName = this.namespaceEncodedName(eventName);
  2879. // Locate the event in the registry.
  2880. var event = node.events.existing[encodedEventName];
  2881. // Build the result descriptor. Omit the `parameters` and `listeners` fields when the
  2882. // parameters or listeners are missing or empty, respectively.
  2883. var eventDescriptor = {};
  2884. if (event.parameters) {
  2885. eventDescriptor.parameters = event.parameters.slice();
  2886. }
  2887. if (event.listeners.existing.length) {
  2888. eventDescriptor.listeners = event.listeners.existing.map(function (eventListenerID) {
  2889. var listener = this.getEventListener(nodeID, eventName, eventListenerID);
  2890. listener.id = eventListenerID;
  2891. return listener;
  2892. }, this);
  2893. }
  2894. this.logger.debugu();
  2895. return eventDescriptor;
  2896. }
  2897. // -- addEventListener ---------------------------------------------------------------------
  2898. /// @name module:vwf.addEventListener
  2899. ///
  2900. /// @see {@link module:vwf/api/kernel.addEventListener}
  2901. addEventListener(nodeID, eventName, eventHandler, eventContextID, eventPhases) {
  2902. let self = this;
  2903. this.logger.debuggx("addEventListener", function () {
  2904. return [nodeID, eventName, self.loggableScript(eventHandler),
  2905. eventContextID, eventPhases
  2906. ];
  2907. });
  2908. var node = self.nodes.existing[nodeID];
  2909. // Encode any namespacing into the name.
  2910. var encodedEventName = this.namespaceEncodedName(eventName);
  2911. // Register the event if this is the first listener added to an event on a prototype.
  2912. if (!node.events.hasOwn(encodedEventName)) {
  2913. node.events.create(encodedEventName, node.initialized && node.patchable);
  2914. }
  2915. // Locate the event in the registry.
  2916. var event = node.events.existing[encodedEventName];
  2917. // Normalize the descriptor.
  2918. eventHandler = this.normalizedHandler(eventHandler, event.parameters);
  2919. // Register the listener.
  2920. var eventListenerID = eventHandler.id || this.sequence(nodeID);
  2921. event.listeners.create(eventListenerID, node.initialized && node.patchable);
  2922. // Call `addingEventListener` on each model.
  2923. this.models.forEach(function (model) {
  2924. model.addingEventListener &&
  2925. model.addingEventListener(nodeID, encodedEventName, eventListenerID,
  2926. eventHandler, eventContextID, eventPhases);
  2927. });
  2928. // Call `addedEventListener` on each view.
  2929. this.views.forEach(function (view) {
  2930. view.addedEventListener &&
  2931. view.addedEventListener(nodeID, encodedEventName, eventListenerID,
  2932. eventHandler, eventContextID, eventPhases);
  2933. });
  2934. this.logger.debugu();
  2935. return eventListenerID;
  2936. }
  2937. // -- removeEventListener ------------------------------------------------------------------
  2938. /// @name module:vwf.removeEventListener
  2939. ///
  2940. /// @see {@link module:vwf/api/kernel.removeEventListener}
  2941. removeEventListener(nodeID, eventName, eventListenerID) {
  2942. let self = this;
  2943. this.logger.debuggx("removeEventListener", function () {
  2944. return [nodeID, eventName, self.loggableScript(eventListenerID)];
  2945. });
  2946. var node = this.nodes.existing[nodeID];
  2947. // Encode any namespacing into the name.
  2948. var encodedEventName = this.namespaceEncodedName(eventName);
  2949. // Locate the event in the registry.
  2950. var event = node.events.existing[encodedEventName];
  2951. // Unregister the listener.
  2952. event.listeners.delete(eventListenerID, node.initialized && node.patchable);
  2953. // Call `removingEventListener` on each model.
  2954. this.models.forEach(function (model) {
  2955. model.removingEventListener &&
  2956. model.removingEventListener(nodeID, encodedEventName, eventListenerID);
  2957. });
  2958. // Call `removedEventListener` on each view.
  2959. this.views.forEach(function (view) {
  2960. view.removedEventListener &&
  2961. view.removedEventListener(nodeID, encodedEventName, eventListenerID);
  2962. });
  2963. this.logger.debugu();
  2964. return eventListenerID;
  2965. }
  2966. // -- setEventListener ---------------------------------------------------------------------
  2967. /// @name module:vwf.setEventListener
  2968. ///
  2969. /// @see {@link module:vwf/api/kernel.setEventListener}
  2970. setEventListener(nodeID, eventName, eventListenerID, eventListener) {
  2971. let self = this;
  2972. this.logger.debuggx("setEventListener", function () {
  2973. return [nodeID, eventName, eventListenerID]; // TODO: loggable eventListener
  2974. });
  2975. var node = this.nodes.existing[nodeID];
  2976. // Encode any namespacing into the name.
  2977. var encodedEventName = this.namespaceEncodedName(eventName);
  2978. // Locate the event in the registry.
  2979. var event = node.events.existing[encodedEventName];
  2980. // Normalize the descriptor.
  2981. eventListener = this.normalizedHandler(eventListener, event.parameters);
  2982. // Record the change.
  2983. if (node.initialized && node.patchable) {
  2984. event.listeners.change(eventListenerID);
  2985. }
  2986. // Call `settingEventListener` on each model. The first model to return a non-undefined
  2987. // value dictates the return value.
  2988. this.models.some(function (model) {
  2989. // Call the driver.
  2990. var listener = model.settingEventListener &&
  2991. model.settingEventListener(nodeID, encodedEventName, eventListenerID, eventListener);
  2992. // Update the value to the value assigned if the driver handled it.
  2993. if (listener !== undefined) {
  2994. eventListener = self.utility.merge({}, listener); // omit `undefined` values
  2995. }
  2996. // Exit the iterator once a driver has handled the assignment.
  2997. return listener !== undefined;
  2998. });
  2999. // Call `satEventListener` on each view.
  3000. this.views.forEach(function (view) {
  3001. view.satEventListener &&
  3002. view.satEventListener(nodeID, encodedEventName, eventListenerID, eventListener);
  3003. });
  3004. this.logger.debugu();
  3005. return eventListener;
  3006. }
  3007. // -- getEventListener ---------------------------------------------------------------------
  3008. /// @name module:vwf.getEventListener
  3009. ///
  3010. /// @see {@link module:vwf/api/kernel.getEventListener}
  3011. getEventListener(nodeID, eventName, eventListenerID) {
  3012. let self = this;
  3013. this.logger.debuggx("getEventListener", function () {
  3014. return [nodeID, eventName, eventListenerID];
  3015. });
  3016. // Encode any namespacing into the name.
  3017. var encodedEventName = this.namespaceEncodedName(eventName);
  3018. // Call `gettingEventListener` on each model. The first model to return a non-undefined
  3019. // value dictates the return value.
  3020. var eventListener = {};
  3021. this.models.some(function (model) {
  3022. // Call the driver.
  3023. var listener = model.gettingEventListener &&
  3024. model.gettingEventListener(nodeID, encodedEventName, eventListenerID);
  3025. // Update the value to the value assigned if the driver handled it.
  3026. if (listener !== undefined) {
  3027. eventListener = self.utility.merge({}, listener); // omit `undefined` values
  3028. }
  3029. // Exit the iterator once a driver has handled the assignment.
  3030. return listener !== undefined;
  3031. });
  3032. // Call `gotEventListener` on each view.
  3033. this.views.forEach(function (view) {
  3034. view.gotEventListener &&
  3035. view.gotEventListener(nodeID, encodedEventName, eventListenerID, eventListener);
  3036. });
  3037. this.logger.debugu();
  3038. return eventListener;
  3039. }
  3040. // -- flushEventListeners ------------------------------------------------------------------
  3041. /// @name module:vwf.flushEventListeners
  3042. ///
  3043. /// @see {@link module:vwf/api/kernel.flushEventListeners}
  3044. flushEventListeners(nodeID, eventName, eventContextID) {
  3045. this.logger.debuggx("flushEventListeners", nodeID, eventName, eventContextID);
  3046. // Encode any namespacing into the name.
  3047. var encodedEventName = this.namespaceEncodedName(eventName);
  3048. // Retrieve the event in case we need to remove listeners from it
  3049. var node = this.nodes.existing[nodeID];
  3050. var event = node.events.existing[encodedEventName];
  3051. // Call `flushingEventListeners` on each model.
  3052. this.models.forEach(function (model) {
  3053. var removedIds = model.flushingEventListeners &&
  3054. model.flushingEventListeners(nodeID, encodedEventName, eventContextID);
  3055. // If the model driver returned an array of the ids of event listeners that it
  3056. // removed, remove their references in the kernel
  3057. if (removedIds && removedIds.length) {
  3058. // Unregister the listeners that were flushed
  3059. removedIds.forEach(function (removedId) {
  3060. event.listeners.delete(removedId, node.initialized && node.patchable);
  3061. });
  3062. }
  3063. });
  3064. // Call `flushedEventListeners` on each view.
  3065. this.views.forEach(function (view) {
  3066. view.flushedEventListeners &&
  3067. view.flushedEventListeners(nodeID, encodedEventName, eventContextID);
  3068. });
  3069. // TODO: `flushEventListeners` can be interpreted by the kernel now and handled with a
  3070. // `removeEventListener` call instead of separate `flushingEventListeners` and
  3071. // `flushedEventListeners` calls to the drivers.
  3072. this.logger.debugu();
  3073. }
  3074. // -- fireEvent ----------------------------------------------------------------------------
  3075. /// @name module:vwf.fireEvent
  3076. ///
  3077. /// @see {@link module:vwf/api/kernel.fireEvent}
  3078. fireEvent(nodeID, eventName, eventParameters) {
  3079. let self = this;
  3080. this.logger.debuggx("fireEvent", function () {
  3081. return [nodeID, eventName, JSON.stringify(self.loggableValues(eventParameters))];
  3082. });
  3083. // Encode any namespacing into the name. (Namespaced names were added in 0.6.21.)
  3084. var encodedEventName = this.namespaceEncodedName(eventName);
  3085. // Call `firingEvent` on each model.
  3086. var handled = this.models.reduce(function (handled, model) {
  3087. return model.firingEvent && model.firingEvent(nodeID, encodedEventName, eventParameters) || handled;
  3088. }, false);
  3089. // Call `firedEvent` on each view.
  3090. this.views.forEach(function (view) {
  3091. view.firedEvent && view.firedEvent(nodeID, encodedEventName, eventParameters);
  3092. });
  3093. this.logger.debugu();
  3094. // TODO: `fireEvent` needs to tell the drivers to invoke each listener individually
  3095. // now that listeners can be spread across multiple drivers.
  3096. return handled;
  3097. }
  3098. // -- dispatchEvent ------------------------------------------------------------------------
  3099. /// Dispatch an event toward a node. Using fireEvent(), capture (down) and bubble (up) along
  3100. /// the path from the global root to the node. Cancel when one of the handlers returns a
  3101. /// truthy value to indicate that it has handled the event.
  3102. ///
  3103. /// @name module:vwf.dispatchEvent
  3104. ///
  3105. /// @see {@link module:vwf/api/kernel.dispatchEvent}
  3106. dispatchEvent(nodeID, eventName, eventParameters, eventNodeParameters) {
  3107. let self = this;
  3108. this.logger.debuggx("dispatchEvent", function () {
  3109. return [nodeID, eventName, JSON.stringify(self.loggableValues(eventParameters)),
  3110. JSON.stringify(self.loggableIndexedValues(eventNodeParameters))
  3111. ];
  3112. });
  3113. // Defaults for the parameters to send with the events. Values from `eventParameters`
  3114. // are sent to each node. `eventNodeParameters` contains additional values to send to
  3115. // specific nodes.
  3116. eventParameters = eventParameters || [];
  3117. eventNodeParameters = eventNodeParameters || {};
  3118. // Find the inheritance path from the node to the root.
  3119. var ancestorIDs = this.ancestors(nodeID);
  3120. var lastAncestorID = "";
  3121. // Make space to record the parameters sent to each node. Parameters provided for upper
  3122. // nodes cascade down until another definition is found for a lower node. We'll remember
  3123. // these on the way down and replay them on the way back up.
  3124. var cascadedEventNodeParameters = {
  3125. "": eventNodeParameters[""] || [] // defaults come from the "" key in eventNodeParameters
  3126. };
  3127. // Parameters passed to the handlers are the concatention of the eventParameters array,
  3128. // the eventNodeParameters for the node (cascaded), and the phase.
  3129. var targetEventParameters = undefined;
  3130. var phase = undefined;
  3131. var handled = false;
  3132. // Capturing phase.
  3133. phase = "capture"; // only handlers tagged "capture" will be invoked
  3134. handled = handled || ancestorIDs.reverse().some(function (ancestorID) { // TODO: reverse updates the array in place every time and we'd rather not
  3135. cascadedEventNodeParameters[ancestorID] = eventNodeParameters[ancestorID] ||
  3136. cascadedEventNodeParameters[lastAncestorID];
  3137. lastAncestorID = ancestorID;
  3138. targetEventParameters =
  3139. eventParameters.concat(cascadedEventNodeParameters[ancestorID], phase);
  3140. targetEventParameters.phase = phase; // smuggle the phase across on the parameters array // TODO: add "phase" as a fireEvent() parameter? it isn't currently needed in the kernel public API (not queueable, not called by the drivers), so avoid if possible
  3141. return this.fireEvent(ancestorID, eventName, targetEventParameters);
  3142. }, this);
  3143. // At target.
  3144. phase = undefined; // invoke all handlers
  3145. cascadedEventNodeParameters[nodeID] = eventNodeParameters[nodeID] ||
  3146. cascadedEventNodeParameters[lastAncestorID];
  3147. targetEventParameters =
  3148. eventParameters.concat(cascadedEventNodeParameters[nodeID], phase);
  3149. handled = handled || this.fireEvent(nodeID, eventName, targetEventParameters);
  3150. // Bubbling phase.
  3151. phase = undefined; // invoke all handlers
  3152. handled = handled || ancestorIDs.reverse().some(function (ancestorID) { // TODO: reverse updates the array in place every time and we'd rather not
  3153. targetEventParameters =
  3154. eventParameters.concat(cascadedEventNodeParameters[ancestorID], phase);
  3155. return this.fireEvent(ancestorID, eventName, targetEventParameters);
  3156. }, this);
  3157. this.logger.debugu();
  3158. }
  3159. // -- execute ------------------------------------------------------------------------------
  3160. /// @name module:vwf.execute
  3161. ///
  3162. /// @see {@link module:vwf/api/kernel.execute}
  3163. execute(nodeID, scriptText, scriptType, callback_async /* result */ ) {
  3164. let self = this;
  3165. this.logger.debuggx("execute", function () {
  3166. return [nodeID, self.loggableScript(scriptText), scriptType];
  3167. });
  3168. // Assume JavaScript if the type is not specified and the text is a string.
  3169. if (!scriptType && (typeof scriptText == "string" || scriptText instanceof String)) {
  3170. scriptType = "application/javascript";
  3171. }
  3172. // Call executing() on each model. The script is considered executed after all models
  3173. // have run.
  3174. var scriptValue = undefined;
  3175. // Watch for any async kernel calls generated as we execute the scriptText and wait for
  3176. // them to complete before calling the callback.
  3177. self.models.kernel.capturingAsyncs(function () {
  3178. self.models.some(function (model) {
  3179. scriptValue = model.executing &&
  3180. model.executing(nodeID, scriptText, scriptType);
  3181. return scriptValue !== undefined;
  3182. });
  3183. // Call executed() on each view to notify view that a script has been executed.
  3184. self.views.forEach(function (view) {
  3185. view.executed && view.executed(nodeID, scriptText, scriptType);
  3186. });
  3187. }, function () {
  3188. callback_async && callback_async(scriptValue);
  3189. });
  3190. this.logger.debugu();
  3191. return scriptValue;
  3192. }
  3193. // -- random -------------------------------------------------------------------------------
  3194. /// @name module:vwf.random
  3195. ///
  3196. /// @see {@link module:vwf/api/kernel.random}
  3197. random(nodeID) {
  3198. return this.models.object.random(nodeID);
  3199. }
  3200. // -- seed ---------------------------------------------------------------------------------
  3201. /// @name module:vwf.seed
  3202. ///
  3203. /// @see {@link module:vwf/api/kernel.seed}
  3204. seed(nodeID, seed) {
  3205. return this.models.object.seed(nodeID, seed);
  3206. }
  3207. // -- time ---------------------------------------------------------------------------------
  3208. /// The current simulation time.
  3209. ///
  3210. /// @name module:vwf.time
  3211. ///
  3212. /// @see {@link module:vwf/api/kernel.time}
  3213. now() {
  3214. return this.virtualTime.now;
  3215. }
  3216. time() {
  3217. return this.virtualTime.now;
  3218. }
  3219. // -- client -------------------------------------------------------------------------------
  3220. /// The moniker of the client responsible for the current action. Will be falsy for actions
  3221. /// originating in the server, such as time ticks.
  3222. ///
  3223. /// @name module:vwf.client
  3224. ///
  3225. /// @see {@link module:vwf/api/kernel.client}
  3226. client() {
  3227. return this.virtualTime.client_;
  3228. }
  3229. // -- moniker ------------------------------------------------------------------------------
  3230. /// The identifer the server assigned to this client.
  3231. ///
  3232. /// @name module:vwf.moniker
  3233. ///
  3234. /// @see {@link module:vwf/api/kernel.moniker}
  3235. moniker() {
  3236. return this.moniker_;
  3237. }
  3238. // -- application --------------------------------------------------------------------------
  3239. /// @name module:vwf.application
  3240. ///
  3241. /// @see {@link module:vwf/api/kernel.application}
  3242. application(initializedOnly) {
  3243. let self = this;
  3244. var applicationID;
  3245. Object.keys(self.nodes.globals).forEach(function (globalID) {
  3246. var global = self.nodes.existing[globalID];
  3247. if ((!initializedOnly || global.initialized) && global.name === "application") {
  3248. applicationID = globalID;
  3249. }
  3250. }, this);
  3251. return applicationID;
  3252. }
  3253. // -- intrinsics ---------------------------------------------------------------------------
  3254. /// @name module:vwf.intrinsics
  3255. ///
  3256. /// @see {@link module:vwf/api/kernel.intrinsics}
  3257. intrinsics(nodeID, result) {
  3258. return this.models.object.intrinsics(nodeID, result);
  3259. }
  3260. // -- uri ----------------------------------------------------------------------------------
  3261. /// @name module:vwf.uri
  3262. ///
  3263. /// @see {@link module:vwf/api/kernel.uri}
  3264. uri(nodeID, searchAncestors, initializedOnly) {
  3265. var uri = this.models.object.uri(nodeID);
  3266. if (searchAncestors) {
  3267. while (!uri && (nodeID = this.parent(nodeID, initializedOnly))) {
  3268. uri = this.models.object.uri(nodeID);
  3269. }
  3270. }
  3271. return uri;
  3272. }
  3273. // -- name ---------------------------------------------------------------------------------
  3274. /// @name module:vwf.name
  3275. ///
  3276. /// @see {@link module:vwf/api/kernel.name}
  3277. name(nodeID) {
  3278. return this.models.object.name(nodeID);
  3279. }
  3280. // -- prototype ----------------------------------------------------------------------------
  3281. /// @name module:vwf.prototype
  3282. ///
  3283. /// @see {@link module:vwf/api/kernel.prototype}
  3284. prototype(nodeID) {
  3285. return this.models.object.prototype(nodeID);
  3286. }
  3287. // -- prototypes ---------------------------------------------------------------------------
  3288. /// @name module:vwf.prototypes
  3289. ///
  3290. /// @see {@link module:vwf/api/kernel.prototypes}
  3291. prototypes(nodeID, includeBehaviors) {
  3292. var prototypes = [];
  3293. do {
  3294. // Add the current node's behaviors.
  3295. if (includeBehaviors) {
  3296. var b = [].concat(this.behaviors(nodeID));
  3297. Array.prototype.push.apply(prototypes, b.reverse());
  3298. }
  3299. // Get the next prototype.
  3300. nodeID = this.prototype(nodeID);
  3301. // Add the prototype.
  3302. if (nodeID) {
  3303. prototypes.push(nodeID);
  3304. }
  3305. } while (nodeID);
  3306. return prototypes;
  3307. }
  3308. // -- behaviors ----------------------------------------------------------------------------
  3309. /// @name module:vwf.behaviors
  3310. ///
  3311. /// @see {@link module:vwf/api/kernel.behaviors}
  3312. behaviors(nodeID) {
  3313. return this.models.object.behaviors(nodeID);
  3314. }
  3315. // -- globals ------------------------------------------------------------------------------
  3316. /// @name module:vwf.globals
  3317. ///
  3318. /// @see {@link module:vwf/api/kernel.globals}
  3319. globals(initializedOnly) {
  3320. let self = this;
  3321. var globals = {};
  3322. Object.keys(self.nodes.globals).forEach(function (globalID) {
  3323. if (!initializedOnly || self.nodes.existing[globalID].initialized) {
  3324. globals[globalID] = undefined;
  3325. }
  3326. }, this);
  3327. return globals;
  3328. }
  3329. // -- global -------------------------------------------------------------------------------
  3330. /// @name module:vwf.global
  3331. ///
  3332. /// @see {@link module:vwf/api/kernel.global}
  3333. global(globalReference, initializedOnly) {
  3334. let self = this;
  3335. var globals = this.globals(initializedOnly);
  3336. // Look for a global node whose URI matches `globalReference`. If there is no match by
  3337. // URI, then search again by name.
  3338. return matches("uri") || matches("name");
  3339. // Look for a global node where the field named by `field` matches `globalReference`.
  3340. function matches(field) {
  3341. var matchingID;
  3342. Object.keys(globals).some(function (globalID) {
  3343. if (self.nodes.existing[globalID][field] === globalReference) {
  3344. matchingID = globalID;
  3345. return true;
  3346. }
  3347. });
  3348. return matchingID;
  3349. }
  3350. }
  3351. // -- root ---------------------------------------------------------------------------------
  3352. /// @name module:vwf.root
  3353. ///
  3354. /// @see {@link module:vwf/api/kernel.root}
  3355. root(nodeID, initializedOnly) {
  3356. var rootID;
  3357. // Walk the ancestors to the top of the tree. Stop when we reach the pseudo-node at the
  3358. // global root, which unlike all other nodes has a falsy ID, or `undefined` if we could
  3359. // not reach the top because `initializedOnly` is set and we attempted to cross between
  3360. // nodes that have and have not completed initialization.
  3361. do {
  3362. rootID = nodeID;
  3363. nodeID = this.parent(nodeID, initializedOnly);
  3364. } while (nodeID);
  3365. // Return the root ID, or `undefined` when `initializedOnly` is set and the node can't
  3366. // see the root.
  3367. return nodeID === undefined ? undefined : rootID;
  3368. }
  3369. // -- ancestors ----------------------------------------------------------------------------
  3370. /// @name module:vwf.ancestors
  3371. ///
  3372. /// @see {@link module:vwf/api/kernel.ancestors}
  3373. ancestors(nodeID, initializedOnly) {
  3374. var ancestors = [];
  3375. nodeID = this.parent(nodeID, initializedOnly);
  3376. while (nodeID) {
  3377. ancestors.push(nodeID);
  3378. nodeID = this.parent(nodeID, initializedOnly);
  3379. }
  3380. return ancestors;
  3381. }
  3382. // -- parent -------------------------------------------------------------------------------
  3383. /// @name module:vwf.parent
  3384. ///
  3385. /// @see {@link module:vwf/api/kernel.parent}
  3386. parent(nodeID, initializedOnly) {
  3387. return this.models.object.parent(nodeID, initializedOnly);
  3388. }
  3389. // -- children -----------------------------------------------------------------------------
  3390. /// @name module:vwf.children
  3391. ///
  3392. /// @see {@link module:vwf/api/kernel.children}
  3393. children(nodeID, initializedOnly) {
  3394. if (nodeID === undefined) {
  3395. this.logger.errorx("children", "cannot retrieve children of nonexistent node");
  3396. return;
  3397. }
  3398. return this.models.object.children(nodeID, initializedOnly);
  3399. }
  3400. // -- child --------------------------------------------------------------------------------
  3401. /// @name module:vwf.child
  3402. ///
  3403. /// @see {@link module:vwf/api/kernel.child}
  3404. child(nodeID, childReference, initializedOnly) {
  3405. var children = this.children(nodeID, initializedOnly);
  3406. if (typeof childReference === "number" || childReference instanceof Number) {
  3407. return children[childReference];
  3408. } else {
  3409. return children.filter(function (childID) {
  3410. return childID && this.name(childID) === childReference;
  3411. }, this)[0];
  3412. }
  3413. }
  3414. // -- descendants --------------------------------------------------------------------------
  3415. /// @name module:vwf.descendants
  3416. ///
  3417. /// @see {@link module:vwf/api/kernel.descendants}
  3418. descendants(nodeID, initializedOnly) {
  3419. if (nodeID === undefined) {
  3420. this.logger.errorx("descendants", "cannot retrieve children of nonexistent node");
  3421. return;
  3422. }
  3423. var descendants = [];
  3424. this.children(nodeID, initializedOnly).forEach(function (childID) {
  3425. descendants.push(childID);
  3426. childID && Array.prototype.push.apply(descendants, this.descendants(childID, initializedOnly));
  3427. }, this);
  3428. return descendants;
  3429. }
  3430. // -- sequence -----------------------------------------------------------------------------
  3431. /// @name module:vwf.sequence
  3432. ///
  3433. /// @see {@link module:vwf/api/kernel.sequence}
  3434. sequence(nodeID) {
  3435. return this.models.object.sequence(nodeID);
  3436. }
  3437. /// Locate nodes matching a search pattern. See vwf.api.kernel#find for details.
  3438. ///
  3439. /// @name module:vwf.find
  3440. ///
  3441. /// @param {ID} nodeID
  3442. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3443. /// is ignored for absolute patterns.
  3444. /// @param {String} matchPattern
  3445. /// The search pattern.
  3446. /// @param {Boolean} [initializedOnly]
  3447. /// Interpret nodes that haven't completed initialization as though they don't have
  3448. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3449. /// applications should never have access to uninitialized parts of the application graph.
  3450. /// @param {Function} [callback]
  3451. /// A callback to receive the search results. If callback is provided, find invokes
  3452. /// callback( matchID ) for each match. Otherwise the result is returned as an array.
  3453. ///
  3454. /// @returns {ID[]|undefined}
  3455. /// If callback is provided, undefined; otherwise an array of the node ids of the result.
  3456. ///
  3457. /// @see {@link module:vwf/api/kernel.find}
  3458. find(nodeID, matchPattern, initializedOnly, callback /* ( matchID ) */ ) {
  3459. // Interpret `find( nodeID, matchPattern, callback )` as
  3460. // `find( nodeID, matchPattern, undefined, callback )`. (`initializedOnly` was added in
  3461. // 0.6.8.)
  3462. if (typeof initializedOnly == "function" || initializedOnly instanceof Function) {
  3463. callback = initializedOnly;
  3464. initializedOnly = undefined;
  3465. }
  3466. // Run the query.
  3467. var matchIDs = find.call(this, nodeID, matchPattern, initializedOnly);
  3468. // Return the result. Invoke the callback if one was provided. Otherwise, return the
  3469. // array directly.
  3470. if (callback) {
  3471. matchIDs.forEach(function (matchID) {
  3472. callback(matchID);
  3473. });
  3474. } else { // TODO: future iterator proxy
  3475. return matchIDs;
  3476. }
  3477. }
  3478. // -- findClients ------------------------------------------------------------------------------
  3479. /// Locate client nodes matching a search pattern.
  3480. ///
  3481. /// @name module:vwf.findClients
  3482. ///
  3483. /// @param {ID} nodeID
  3484. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3485. /// is ignored for absolute patterns.
  3486. /// @param {String} matchPattern
  3487. /// The search pattern.
  3488. /// @param {Function} [callback]
  3489. /// A callback to receive the search results. If callback is provided, find invokes
  3490. /// callback( matchID ) for each match. Otherwise the result is returned as an array.
  3491. ///
  3492. /// @returns {ID[]|undefined}
  3493. /// If callback is provided, undefined; otherwise an array of the node ids of the result.
  3494. ///
  3495. /// @deprecated in version 0.6.21. Instead of `kernel.findClients( reference, "/pattern" )`,
  3496. /// use `kernel.find( reference, "doc('http://vwf.example.com/clients.vwf')/pattern" )`.
  3497. ///
  3498. /// @see {@link module:vwf/api/kernel.findClients}
  3499. findClients(nodeID, matchPattern, callback /* ( matchID ) */ ) {
  3500. this.logger.warn("`kernel.findClients` is deprecated. Use " +
  3501. "`kernel.find( nodeID, \"doc('proxy/clients.vwf')/pattern\" )`" +
  3502. " instead.");
  3503. var clientsMatchPattern = "doc('proxy/clients.vwf')" +
  3504. (matchPattern[0] === "/" ? "" : "/") + matchPattern;
  3505. return this.find(nodeID || this.application(), clientsMatchPattern, callback);
  3506. }
  3507. /// Test a node against a search pattern. See vwf.api.kernel#test for details.
  3508. ///
  3509. /// @name module:vwf.test
  3510. ///
  3511. /// @param {ID} nodeID
  3512. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3513. /// is ignored for absolute patterns.
  3514. /// @param {String} matchPattern
  3515. /// The search pattern.
  3516. /// @param {ID} testID
  3517. /// A node to test against the pattern.
  3518. /// @param {Boolean} [initializedOnly]
  3519. /// Interpret nodes that haven't completed initialization as though they don't have
  3520. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3521. /// applications should never have access to uninitialized parts of the application graph.
  3522. ///
  3523. /// @returns {Boolean}
  3524. /// true when testID matches the pattern.
  3525. ///
  3526. /// @see {@link module:vwf/api/kernel.test}
  3527. test(nodeID, matchPattern, testID, initializedOnly) {
  3528. // Run the query.
  3529. var matchIDs = this.find.call(this, nodeID, matchPattern, initializedOnly);
  3530. // Search for the test node in the result.
  3531. return matchIDs.some(function (matchID) {
  3532. return matchID == testID;
  3533. });
  3534. }
  3535. // == Private functions ====================================================================
  3536. // -- loadComponent ------------------------------------------------------------------------
  3537. /// @name module:vwf~loadComponent
  3538. loadComponent(nodeURI, baseURI, callback_async /* nodeDescriptor */ , errback_async /* errorMessage */ ) { // TODO: turn this into a generic xhr loader exposed as a kernel function?
  3539. let self = this;
  3540. if (nodeURI == self.kutility.protoNodeURI) {
  3541. callback_async(self.kutility.protoNodeDescriptor);
  3542. } else if (nodeURI.match(RegExp("^data:application/json;base64,"))) {
  3543. // Primarly for testing, parse one specific form of data URIs. We need to parse
  3544. // these ourselves since Chrome can't load data URIs due to cross origin
  3545. // restrictions.
  3546. callback_async(JSON.parse(atob(nodeURI.substring(29)))); // TODO: support all data URIs
  3547. } else {
  3548. self.virtualTime.suspend("while loading " + nodeURI); // suspend the queue
  3549. let fetchUrl = self.remappedURI(nodeURI, baseURI);
  3550. let dbName = fetchUrl.split(".").join("_");
  3551. const parseComp = function (f) {
  3552. let result = JSON.parse(f);
  3553. let nativeObject = result;
  3554. // console.log(nativeObject);
  3555. if (nativeObject) {
  3556. callback_async(nativeObject);
  3557. self.virtualTime.resume("after loading " + nodeURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3558. } else {
  3559. self.logger.warnx("loadComponent", "error loading", nodeURI + ":", error);
  3560. errback_async(error);
  3561. self.virtualTime.resume("after loading " + nodeURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3562. }
  3563. }
  3564. //var fileName = "";
  3565. // let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  3566. if (dbName.includes("proxy")) {
  3567. //userDB = await window._LCS_SYS_USER.get('proxy').then();
  3568. let proxyDB = self.proxy ? _LCSDB.user(self.proxy) : _LCSDB.user(_LCS_WORLD_USER.pub);
  3569. let fileName = dbName + '_json';
  3570. let dbNode = proxyDB.get('proxy').get(fileName);
  3571. let nodeProm = new Promise(res => dbNode.once(res));
  3572. nodeProm.then(comp => {
  3573. parseComp(comp);
  3574. })
  3575. // (function(r){
  3576. // //console.log(r);
  3577. // parseComp(r);
  3578. // });
  3579. } else {
  3580. let worldName = dbName.split('/')[1];
  3581. let fileName = dbName.split('/')[2] + '_json';
  3582. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').path(worldName).get(fileName);
  3583. let nodeProm = new Promise(res => dbNode.once(res))
  3584. nodeProm.then(comp => {
  3585. parseComp(comp);
  3586. })
  3587. // (function(r){
  3588. // //console.log(r);
  3589. // parseComp(r);
  3590. // });
  3591. }
  3592. //console.log(source);
  3593. //userDB.get(fileName).once(async function(res) {
  3594. // }, {wait: 1000})
  3595. }
  3596. }
  3597. // -- loadScript ---------------------------------------------------------------------------
  3598. /// @name module:vwf~loadScript
  3599. loadScript(scriptURI, baseURI, callback_async /* scriptText */ , errback_async /* errorMessage */ ) {
  3600. let self = this;
  3601. if (scriptURI.match(RegExp("^data:application/javascript;base64,"))) {
  3602. // Primarly for testing, parse one specific form of data URIs. We need to parse
  3603. // these ourselves since Chrome can't load data URIs due to cross origin
  3604. // restrictions.
  3605. callback_async(atob(scriptURI.substring(35))); // TODO: support all data URIs
  3606. } else {
  3607. self.virtualTime.suspend("while loading " + scriptURI); // suspend the queue
  3608. let fetchUrl = self.remappedURI(scriptURI, baseURI);
  3609. let dbName = fetchUrl.split(".").join("_")
  3610. const parseComp = function (res) {
  3611. let scriptText = res;
  3612. try {
  3613. callback_async(scriptText);
  3614. self.virtualTime.resume("after loading " + scriptURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3615. } catch (e) {
  3616. self.logger.warnx("loadScript", "error loading", scriptURI + ":", error);
  3617. errback_async(error);
  3618. self.virtualTime.resume("after loading " + scriptURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3619. }
  3620. }
  3621. let worldName = dbName.split('/')[1];
  3622. //let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  3623. if (dbName.includes("proxy")) {
  3624. let proxyDB = self.proxy ? _LCSDB.user(self.proxy) : _LCSDB.user(_LCS_WORLD_USER.pub);
  3625. //userDB = window._LCS_SYS_USER.get('proxy');
  3626. let fileName = dbName;
  3627. let dbNode = proxyDB.get('proxy').get(fileName);
  3628. let nodeProm = new Promise(res => dbNode.once(res))
  3629. nodeProm.then(comp => {
  3630. parseComp(comp);
  3631. })
  3632. // window._LCS_SYS_USER.get('proxy').get(fileName).get('file').once(function(r){
  3633. // //console.log(r);
  3634. // parseComp(r);
  3635. // });
  3636. } else {
  3637. let fileName = dbName.split('/')[2]; //dbName.replace(worldName + '/', "");
  3638. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').path(worldName).get(fileName);
  3639. let nodeProm = new Promise(res => dbNode.once(res))
  3640. nodeProm.then(comp => {
  3641. parseComp(comp);
  3642. })
  3643. // userDB.get('worlds').path(worldName).get(fileName).get('file').once(function(r){
  3644. // //console.log(r);
  3645. // parseComp(r);
  3646. // });
  3647. }
  3648. // userDB.get(fileName).once(, {wait: 1000})
  3649. }
  3650. }
  3651. /// Determine if a given property of a node has a setter function, either directly on the
  3652. /// node or inherited from a prototype.
  3653. ///
  3654. /// This function must run as a method of the kernel. Invoke as: nodePropertyHasSetter.call(
  3655. /// kernel, nodeID, propertyName ).
  3656. ///
  3657. /// @name module:vwf~nodePropertyHasSetter
  3658. ///
  3659. /// @param {ID} nodeID
  3660. /// @param {String} propertyName
  3661. ///
  3662. /// @returns {Boolean}
  3663. nodePropertyHasSetter(nodeID, propertyName) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript; need to delegate to all script drivers
  3664. var node = this.models.javascript.nodes[nodeID];
  3665. var setter = node.private.setters && node.private.setters[propertyName];
  3666. return typeof setter == "function" || setter instanceof Function;
  3667. }
  3668. /// Determine if a given property of a node has a setter function. The node's prototypes are
  3669. /// not considered.
  3670. ///
  3671. /// This function must run as a method of the kernel. Invoke as:
  3672. /// nodePropertyHasOwnSetter.call( kernel, nodeID, propertyName ).
  3673. ///
  3674. /// @name module:vwf~nodePropertyHasOwnSetter
  3675. ///
  3676. /// @param {ID} nodeID
  3677. /// @param {String} propertyName
  3678. ///
  3679. /// @returns {Boolean}
  3680. nodePropertyHasOwnSetter(nodeID, propertyName) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript; need to delegate to all script drivers
  3681. var node = this.models.javascript.nodes[nodeID];
  3682. var setter = node.private.setters && node.private.setters.hasOwnProperty(propertyName) && node.private.setters[propertyName];
  3683. return typeof setter == "function" || setter instanceof Function;
  3684. }
  3685. /// Determine if a node has a child with the given name, either directly on the node or
  3686. /// inherited from a prototype.
  3687. ///
  3688. /// This function must run as a method of the kernel. Invoke as: nodeHasChild.call(
  3689. /// kernel, nodeID, childName ).
  3690. ///
  3691. /// @name module:vwf~nodeHasChild
  3692. ///
  3693. /// @param {ID} nodeID
  3694. /// @param {String} childName
  3695. ///
  3696. /// @returns {Boolean}
  3697. nodeHasChild(nodeID, childName) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript
  3698. var node = this.models.javascript.nodes[nodeID];
  3699. return childName in node.children;
  3700. }
  3701. /// Determine if a node has a child with the given name. The node's prototypes are not
  3702. /// considered.
  3703. ///
  3704. /// This function must run as a method of the kernel. Invoke as: nodeHasOwnChild.call(
  3705. /// kernel, nodeID, childName ).
  3706. ///
  3707. /// @name module:vwf~nodeHasOwnChild
  3708. ///
  3709. /// @param {ID} nodeID
  3710. /// @param {String} childName
  3711. ///
  3712. /// @returns {Boolean}
  3713. nodeHasOwnChild(nodeID, childName) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript
  3714. var node = this.models.javascript.nodes[nodeID];
  3715. var hasChild = false;
  3716. if (parseInt(childName).toString() !== childName) {
  3717. hasChild = node.children.hasOwnProperty(childName); // TODO: this is peeking inside of vwf-model-javascript
  3718. } else {
  3719. // Children with numeric names do not get added as properties of the children array, so loop over the children
  3720. // to check manually
  3721. for (var i = 0, il = node.children.length; i < il; i++) {
  3722. if (childName === node.children[i].name) {
  3723. hasChild = true;
  3724. }
  3725. }
  3726. }
  3727. return hasChild;
  3728. }
  3729. /// Determine if a component specifier is a URI.
  3730. ///
  3731. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3732. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3733. ///
  3734. /// @name module:vwf~componentIsURI
  3735. ///
  3736. /// @param {String|Object} candidate
  3737. ///
  3738. /// @returns {Boolean}
  3739. componentIsURI(candidate) {
  3740. return (typeof candidate == "string" || candidate instanceof String) && !this.componentIsID(candidate);
  3741. }
  3742. /// Determine if a component specifier is a descriptor.
  3743. ///
  3744. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3745. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3746. ///
  3747. /// @name module:vwf~componentIsDescriptor
  3748. ///
  3749. /// @param {String|Object} candidate
  3750. ///
  3751. /// @returns {Boolean}
  3752. componentIsDescriptor(candidate) {
  3753. return typeof candidate == "object" && candidate != null && !this.isPrimitive(candidate);
  3754. }
  3755. /// Determine if a component specifier is an ID.
  3756. ///
  3757. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3758. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3759. ///
  3760. /// @name module:vwf~componentIsID
  3761. ///
  3762. /// @param {String|Object} candidate
  3763. ///
  3764. /// @returns {Boolean}
  3765. componentIsID(candidate) {
  3766. return this.isPrimitive(candidate) && this.models.object.exists(candidate) &&
  3767. !(this.components[candidate] instanceof Array);
  3768. }
  3769. /// Determine if a value is a JavaScript primitive, or the boxed version of a JavaScript
  3770. /// primitive.
  3771. ///
  3772. /// Node IDs are JavaScript primitives. This function may be used to determine if a value
  3773. /// has the correct type to be a node ID.
  3774. ///
  3775. /// @name module:vwf~isPrimitive
  3776. ///
  3777. /// @param candidate
  3778. ///
  3779. /// @returns {Boolean}
  3780. isPrimitive(candidate) {
  3781. switch (typeof candidate) {
  3782. case "string":
  3783. case "number":
  3784. case "boolean":
  3785. return true;
  3786. case "object":
  3787. return candidate instanceof String || candidate instanceof Number ||
  3788. candidate instanceof Boolean;
  3789. default:
  3790. return false;
  3791. }
  3792. }
  3793. /// Determine if an object is a component descriptor. Detect the type by searching for
  3794. /// descriptor keys in the candidate object.
  3795. ///
  3796. /// @name module:vwf~objectIsComponent
  3797. ///
  3798. /// @param {Object} candidate
  3799. ///
  3800. /// @returns {Boolean}
  3801. objectIsComponent(candidate) {
  3802. var componentAttributes = [
  3803. "extends",
  3804. "implements",
  3805. "source",
  3806. "type",
  3807. "properties",
  3808. "methods",
  3809. "events",
  3810. "children",
  3811. "scripts",
  3812. ];
  3813. var isComponent = false;
  3814. if (typeof candidate == "object" && candidate != null) {
  3815. isComponent = componentAttributes.some(function (attributeName) {
  3816. return candidate.hasOwnProperty(attributeName);
  3817. });
  3818. }
  3819. return isComponent;
  3820. }
  3821. /// Determine if a property initializer is a detailed initializer containing explicit
  3822. /// accessor and value parameters (rather than a simple value specification). Detect the
  3823. /// type by searching for property initializer keys in the candidate object.
  3824. ///
  3825. /// @name module:vwf~valueHasAccessors
  3826. ///
  3827. /// @param {Object} candidate
  3828. ///
  3829. /// @returns {Boolean}
  3830. valueHasAccessors(candidate) {
  3831. var accessorAttributes = [
  3832. "get",
  3833. "set",
  3834. "value",
  3835. "node",
  3836. "create",
  3837. "undefined",
  3838. ];
  3839. var hasAccessors = false;
  3840. if (typeof candidate == "object" && candidate != null) {
  3841. hasAccessors = accessorAttributes.some(function (attributeName) {
  3842. return candidate.hasOwnProperty(attributeName);
  3843. });
  3844. }
  3845. return hasAccessors;
  3846. }
  3847. /// Determine if a method or event initializer is a detailed initializer containing a
  3848. /// parameter list along with the body text (method initializers only). Detect the type by
  3849. /// searching for method and event initializer keys in the candidate object.
  3850. ///
  3851. /// @name module:vwf~valueHasBody
  3852. ///
  3853. /// @param {Object} candidate
  3854. ///
  3855. /// @returns {Boolean}
  3856. valueHasBody(candidate) { // TODO: refactor and share with valueHasAccessors and possibly objectIsComponent // TODO: unlike a property initializer, we really only care if it's an object vs. text; text == use as body; object == presume o.parameters and o.body // TODO: except that a script in the unnamed-list format would appear as an object but should be used as the body
  3857. var bodyAttributes = [
  3858. "parameters",
  3859. "body",
  3860. "listeners",
  3861. ];
  3862. var hasBody = false; // TODO: "body" term is confusing, but that's the current terminology used in vwf/model/javascript
  3863. if (typeof candidate == "object" && candidate != null) {
  3864. hasBody = bodyAttributes.some(function (attributeName) {
  3865. return candidate.hasOwnProperty(attributeName);
  3866. });
  3867. }
  3868. return hasBody;
  3869. }
  3870. /// Determine if a script initializer is a detailed initializer containing explicit text and
  3871. /// type parameters (rather than being a simple text specification). Detect the type by
  3872. /// searching for the script initializer keys in the candidate object.
  3873. ///
  3874. /// @name module:vwf~valueHasType
  3875. ///
  3876. /// @param {Object} candidate
  3877. ///
  3878. /// @returns {Boolean}
  3879. valueHasType(candidate) { // TODO: refactor and share with valueHasBody, valueHasAccessors and possibly objectIsComponent
  3880. var typeAttributes = [
  3881. "source",
  3882. "text",
  3883. "type",
  3884. ];
  3885. var hasType = false;
  3886. if (typeof candidate == "object" && candidate != null) {
  3887. hasType = typeAttributes.some(function (attributeName) {
  3888. return candidate.hasOwnProperty(attributeName);
  3889. });
  3890. }
  3891. return hasType;
  3892. }
  3893. /// Convert a potentially-namespaced member name into a string such that a namespaced name
  3894. /// will be distinct from an encoded name in any other namespace, or from any simple name
  3895. /// not having a namespace.
  3896. ///
  3897. /// Simple names are strings such as `"name"`. Namespaced names are arrays of strings, such
  3898. /// as `[ "ns", "name" ]` or `[ "outer", "inner", "name" ]`. An array containing a single
  3899. /// string, such as `[ "name" ]`, is not namespaced and is the same name as `"name"`.
  3900. ///
  3901. /// Each of the following encodes into a distinct value:
  3902. ///
  3903. /// `"name"` or `[ "name" ]`
  3904. /// `[ "a", "name" ]`
  3905. /// `[ "b", "name" ]`
  3906. /// `[ "a", "a", "name" ]`
  3907. /// `[ "a", "b", "name" ]`
  3908. /// `[ "b", "b", "name" ]`
  3909. /// *etc.*
  3910. ///
  3911. /// @name module:vwf~namespaceEncodedName
  3912. ///
  3913. /// @param {String|String[]} memberName
  3914. /// A string, or an array of strings containing a name preceded by any number of namespace
  3915. /// names. In an array, each element defines a unique space for the member name and for
  3916. /// any intermediate namespaces.
  3917. ///
  3918. /// @returns {String}
  3919. namespaceEncodedName(memberName) {
  3920. if (typeof memberName === "object" && memberName instanceof Array) {
  3921. return (memberName.length !== 1) ? "vwf$" + memberName.join("$") : memberName[0];
  3922. } else {
  3923. return memberName;
  3924. }
  3925. }
  3926. /// Convert a (potentially-abbreviated) component specification to a descriptor parsable by
  3927. /// vwf.createChild. The following forms are accepted:
  3928. ///
  3929. /// - Descriptor: { extends: component, source: ..., type: ..., ... }
  3930. /// - Component URI: http://host/path/to/component.vwf
  3931. /// - Asset URI: http://host/ath/to/asset.type
  3932. /// - Node ID
  3933. ///
  3934. /// They are converted as follows:
  3935. ///
  3936. /// - Descriptor: unchanged [1]
  3937. /// - Component URI: a component that extends the component identified by the URI
  3938. /// - Asset URI: a component having the asset identified by the URI as its source
  3939. /// - Node ID: a component that extends the previously-created node identified by the ID
  3940. ///
  3941. /// [1] As a special case, missing MIME types are filled in for assets matcching the
  3942. /// patterns *.unity3d and *.dae, and components having assets of those types but no
  3943. /// prototype declared will be upgraded to extend scene.vwf and navscene.vwf, respectively.
  3944. ///
  3945. /// @name module:vwf~normalizedComponent
  3946. ///
  3947. /// @param {String|Object} component
  3948. ///
  3949. /// @returns {Object}
  3950. normalizedComponent(component) {
  3951. // Convert a component URI to an instance of that type or an asset reference to an
  3952. // untyped reference to that asset. Convert a component ID to an instance of that
  3953. // prototype.
  3954. if (this.componentIsURI(component)) {
  3955. if (component.match(/\.vwf$/)) { // TODO: detect component from mime-type instead of extension?
  3956. component = {
  3957. extends: component
  3958. };
  3959. } else {
  3960. component = {
  3961. source: component
  3962. };
  3963. }
  3964. } else if (this.componentIsID(component)) {
  3965. component = {
  3966. extends: component
  3967. };
  3968. }
  3969. // Fill in the mime type from the source specification if not provided.
  3970. if (component.source && !component.type) { // TODO: validate component
  3971. var match = component.source.match(/\.([^.]*)$/); // TODO: get type from mime-type (from server if remote, from os if local, or (?) from this internal table otherwise)
  3972. if (match) {
  3973. switch (match[1]) {
  3974. case "unity3d":
  3975. component.type = "application/vnd.unity";
  3976. break;
  3977. case "dae":
  3978. component.type = "model/vnd.collada+xml";
  3979. break;
  3980. }
  3981. }
  3982. }
  3983. // Fill in the component type from the mime type if not provided.
  3984. if (component.type && !component.extends) { // TODO: load from a server configuration file
  3985. switch (component.type) {
  3986. case "application/vnd.unity":
  3987. component.extends = "http://vwf.example.com/scene.vwf";
  3988. break;
  3989. case "model/vnd.collada+xml":
  3990. component.extends = "http://vwf.example.com/navscene.vwf";
  3991. break;
  3992. }
  3993. }
  3994. return component;
  3995. }
  3996. /// Convert a `Handler` specification into the standard form of an object containing
  3997. /// `parameters`, `body` and `type` fields.
  3998. ///
  3999. /// @name module:vwf~normalizedHandler
  4000. ///
  4001. /// @param {Handler|string}
  4002. /// @param {string[]} [defaultParameters]
  4003. ///
  4004. /// @returns {Handler}
  4005. normalizedHandler(handler, defaultParameters) {
  4006. // Convert abbreviated forms to the explict `Handler` form.
  4007. if (typeof handler !== "object" || handler instanceof Array) {
  4008. handler = {
  4009. body: handler
  4010. }; //if (require("vwf/configuration").active["preserve-script-closures"]
  4011. } else if (this.configuration["preserve-script-closures"] && (typeof handler == "function" || handler instanceof Function)) {
  4012. handler = {
  4013. body: handler
  4014. };
  4015. }
  4016. // Use a default parameter list if the handler doesn't provide its own and if defaults
  4017. // were provided.
  4018. if (!handler.parameters && defaultParameters) {
  4019. handler.parameters = defaultParameters;
  4020. }
  4021. // Fill in a default media type if `type` is not provided. A `body` of type `string` is
  4022. // taken to be `application/javascript`.
  4023. if (handler.type === undefined) {
  4024. if (typeof handler.body === "string" || handler.body instanceof String) {
  4025. handler.type = "application/javascript";
  4026. }
  4027. }
  4028. return handler;
  4029. }
  4030. /// Convert a `fields` object as passed between the client and reflector and stored in the
  4031. /// message queue into a form suitable for writing to a log.
  4032. ///
  4033. /// @name module:vwf~loggableFields
  4034. ///
  4035. /// @param {Object} fields
  4036. ///
  4037. /// @returns {Object}
  4038. loggableFields(fields) {
  4039. return this.utility.transform(fields, this.utility.transforms.transit);
  4040. }
  4041. /// Convert a component URI, descriptor or ID into a form suitable for writing to a log.
  4042. ///
  4043. /// @name module:vwf~loggableComponent
  4044. ///
  4045. /// @param {String|Object} component
  4046. ///
  4047. /// @returns {String|Object}
  4048. loggableComponent(component) {
  4049. return this.utility.transform(component, this.loggableComponentTransformation);
  4050. }
  4051. /// Convert an arbitrary JavaScript value into a form suitable for writing to a log.
  4052. ///
  4053. /// @name module:vwf~loggableValue
  4054. ///
  4055. /// @param {Object} value
  4056. ///
  4057. /// @returns {Object}
  4058. loggableValue(value) {
  4059. let self = this;
  4060. return this.utility.transform(value, function (object, names, depth) {
  4061. object = self.utility.transforms.transit(object, names, depth);
  4062. return typeof object == "number" ? Number(object.toPrecision(5)) : object; // reduce numeric precision to remove visual noise
  4063. });
  4064. }
  4065. /// Convert an array of arbitrary JavaScript values into a form suitable for writing to a
  4066. /// log.
  4067. ///
  4068. /// @name module:vwf~loggableValues
  4069. ///
  4070. /// @param {Object[]|undefined} values
  4071. ///
  4072. /// @returns {Object[]|undefined}
  4073. loggableValues(values) {
  4074. return this.loggableValue(values);
  4075. }
  4076. /// Convert an object indexing arrays of arbitrary JavaScript values into a form suitable
  4077. /// for writing to a log.
  4078. ///
  4079. /// @name module:vwf~loggableIndexedValues
  4080. ///
  4081. /// @param {Object|undefined} values
  4082. ///
  4083. /// @returns {Object|undefined}
  4084. loggableIndexedValues(values) {
  4085. return this.loggableValue(values);
  4086. }
  4087. /// Convert script text into a form suitable for writing to a log.
  4088. ///
  4089. /// @name module:vwf~loggableScript
  4090. ///
  4091. /// @param {String|undefined} script
  4092. ///
  4093. /// @returns {String}
  4094. loggableScript(script) {
  4095. return (script || "").replace(/\s+/g, " ").substring(0, 100);
  4096. }
  4097. // -- remappedURI --------------------------------------------------------------------------
  4098. /// Remap a component URI to its location in a local cache.
  4099. ///
  4100. /// http://vwf.example.com/component.vwf => http://localhost/proxy/vwf.example.com/component.vwf
  4101. ///
  4102. /// @name module:vwf~remappedURI
  4103. remappedURI(uri, baseURI) {
  4104. // var match = uri.match( RegExp( "http://(vwf.example.com)/(.*)" ) );
  4105. // if ( match ) {
  4106. // uri = window.location.protocol + "//" + window.location.host +
  4107. // "/proxy/" + match[1] + "/" + match[2];
  4108. // }
  4109. if (baseURI && uri[0] !== "/") {
  4110. let newURI = "";
  4111. let parts = baseURI.split('/');
  4112. parts[parts.length - 1] = uri;
  4113. parts.map(el => {
  4114. newURI = newURI + el + '/';
  4115. })
  4116. return newURI.slice(0, -1)
  4117. }
  4118. return uri
  4119. }
  4120. // -- resolvedDescriptor -------------------------------------------------------------------
  4121. /// Resolve relative URIs in a component descriptor.
  4122. ///
  4123. /// @name module:vwf~resolvedDescriptor
  4124. resolvedDescriptor(component, baseURI) {
  4125. return this.utility.transform(component, resolvedDescriptorTransformationWithBaseURI);
  4126. function resolvedDescriptorTransformationWithBaseURI(object, names, depth) {
  4127. return resolvedDescriptorTransformation.call(this, object, names, depth, baseURI);
  4128. }
  4129. }
  4130. // -- loggableComponentTransformation ------------------------------------------------------
  4131. /// vwf/utility/transform() transformation function to truncate the verbose bits of a
  4132. /// component so that it may be written to a log.
  4133. ///
  4134. /// @name module:vwf~loggableComponentTransformation
  4135. loggableComponentTransformation(object, names, depth) {
  4136. // Get our bearings at the current recusion level.
  4137. var markers = this.descriptorMarkers(object, names, depth);
  4138. // Transform the object here.
  4139. switch (markers.containerName) {
  4140. case "extends":
  4141. // Omit a component descriptor for the prototype.
  4142. if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {
  4143. return {};
  4144. }
  4145. break;
  4146. case "implements":
  4147. // Omit component descriptors for the behaviors.
  4148. if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {
  4149. return {};
  4150. }
  4151. break;
  4152. case "properties":
  4153. // Convert property values to a loggable version, and omit getter and setter
  4154. // text.
  4155. if (markers.memberIndex == 0 && !this.valueHasAccessors(object) ||
  4156. markers.memberIndex == 1 && names[0] == "value") {
  4157. return this.loggableValue(object);
  4158. } else if (markers.memberIndex == 1 && (names[0] == "get" || names[0] == "set")) {
  4159. return "...";
  4160. }
  4161. break;
  4162. case "methods":
  4163. // Omit method body text.
  4164. if (markers.memberIndex == 0 && !this.valueHasBody(object) ||
  4165. markers.memberIndex == 1 && names[0] == "body") {
  4166. return "...";
  4167. }
  4168. break;
  4169. case "events":
  4170. // Nothing for events.
  4171. break;
  4172. case "children":
  4173. // Omit child component descriptors.
  4174. if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {
  4175. return {};
  4176. }
  4177. break;
  4178. case "scripts":
  4179. // Shorten script text.
  4180. if (markers.memberIndex == 0 && !this.valueHasType(object) ||
  4181. markers.memberIndex == 1 && names[0] == "text") {
  4182. return "...";
  4183. }
  4184. break;
  4185. }
  4186. return object;
  4187. }
  4188. // -- resolvedDescriptorTransformation -----------------------------------------------------
  4189. /// vwf/utility/transform() transformation function to resolve relative URIs in a component
  4190. /// descriptor.
  4191. ///
  4192. /// @name module:vwf~resolvedDescriptorTransformation
  4193. resolvedDescriptorTransformation(object, names, depth, baseURI) {
  4194. // Get our bearings at the current recusion level.
  4195. var markers = this.descriptorMarkers(object, names, depth);
  4196. // Resolve all the URIs.
  4197. switch (markers.containerName) {
  4198. case "extends":
  4199. case "implements":
  4200. case "source":
  4201. case "children":
  4202. if (markers.memberIndex == 0 && this.componentIsURI(object)) {
  4203. return object //require( "vwf/utility" ).resolveURI( object, baseURI );
  4204. }
  4205. break;
  4206. case "scripts":
  4207. if (markers.memberIndex == 1 && names[0] == "source") {
  4208. return object //require( "vwf/utility" ).resolveURI( object, baseURI );
  4209. }
  4210. break;
  4211. }
  4212. return object;
  4213. }
  4214. // -- descriptorMarkers --------------------------------------------------------------------
  4215. /// Locate the closest container (`properties`, `methods`, `events`, `children`) and
  4216. /// contained member in a `vwf/utility/transform` iterator call on a component descriptor.
  4217. ///
  4218. /// @name module:vwf~descriptorMarkers
  4219. descriptorMarkers(object, names, depth) {
  4220. // Find the index of the lowest nested component in the names list.
  4221. var componentIndex = names.length;
  4222. while (componentIndex > 2 && names[componentIndex - 1] == "children") {
  4223. componentIndex -= 2;
  4224. }
  4225. // depth names notes
  4226. // ----- ----- -----
  4227. // 0: [] the component
  4228. // 1: [ "properties" ] its properties object
  4229. // 2: [ "propertyName", "properties" ] one property
  4230. // 1: [ "children" ] the children object
  4231. // 2: [ "childName", "children" ] one child
  4232. // 3: [ "properties", "childName", "children" ] the child's properties
  4233. // 4: [ "propertyName", "properties", "childName", "children" ] one child property
  4234. if (componentIndex > 0) {
  4235. // Locate the container ("properties", "methods", "events", etc.) below the
  4236. // component in the names list.
  4237. var containerIndex = componentIndex - 1;
  4238. var containerName = names[containerIndex];
  4239. // Locate the member as appropriate for the container.
  4240. if (containerName == "extends") {
  4241. var memberIndex = containerIndex;
  4242. var memberName = names[memberIndex];
  4243. } else if (containerName == "implements") {
  4244. if (containerIndex > 0) {
  4245. if (typeof names[containerIndex - 1] == "number") {
  4246. var memberIndex = containerIndex - 1;
  4247. var memberName = names[memberIndex];
  4248. } else {
  4249. var memberIndex = containerIndex;
  4250. var memberName = undefined;
  4251. }
  4252. } else if (typeof object != "object" || !(object instanceof Array)) {
  4253. var memberIndex = containerIndex;
  4254. var memberName = undefined;
  4255. }
  4256. } else if (containerName == "source" || containerName == "type") {
  4257. var memberIndex = containerIndex;
  4258. var memberName = names[memberIndex];
  4259. } else if (containerName == "properties" || containerName == "methods" || containerName == "events" ||
  4260. containerName == "children") {
  4261. if (containerIndex > 0) {
  4262. var memberIndex = containerIndex - 1;
  4263. var memberName = names[memberIndex];
  4264. }
  4265. } else if (containerName == "scripts") {
  4266. if (containerIndex > 0) {
  4267. if (typeof names[containerIndex - 1] == "number") {
  4268. var memberIndex = containerIndex - 1;
  4269. var memberName = names[memberIndex];
  4270. } else {
  4271. var memberIndex = containerIndex;
  4272. var memberName = undefined;
  4273. }
  4274. } else if (typeof object != "object" || !(object instanceof Array)) {
  4275. var memberIndex = containerIndex;
  4276. var memberName = undefined;
  4277. }
  4278. } else {
  4279. containerIndex = undefined;
  4280. containerName = undefined;
  4281. }
  4282. }
  4283. return {
  4284. containerIndex: containerIndex,
  4285. containerName: containerName,
  4286. memberIndex: memberIndex,
  4287. memberName: memberName,
  4288. };
  4289. }
  4290. /// Locate nodes matching a search pattern. {@link module:vwf/api/kernel.find} describes the
  4291. /// supported patterns.
  4292. ///
  4293. /// This is the internal implementation used by {@link module:vwf.find} and
  4294. /// {@link module:vwf.test}.
  4295. ///
  4296. /// This function must run as a method of the kernel. Invoke it as:
  4297. /// `find.call( kernel, nodeID, matchPattern, initializedOnly )`.
  4298. ///
  4299. /// @name module:vwf~find
  4300. ///
  4301. /// @param {ID} nodeID
  4302. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  4303. /// is ignored for absolute patterns.
  4304. /// @param {String} matchPattern
  4305. /// The search pattern.
  4306. /// @param {Boolean} [initializedOnly]
  4307. /// Interpret nodes that haven't completed initialization as though they don't have
  4308. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  4309. /// applications should never have access to uninitialized parts of the application graph.
  4310. ///
  4311. /// @returns {ID[]|undefined}
  4312. /// An array of the node ids of the result.
  4313. find(nodeID, matchPattern, initializedOnly) {
  4314. // Evaluate the expression using the provided node as the reference. Take the root node
  4315. // to be the root of the reference node's tree. If a reference node is not provided, use
  4316. // the application as the root.
  4317. var rootID = nodeID ? this.root(nodeID, initializedOnly) :
  4318. this.application(initializedOnly);
  4319. return this.xpath.resolve(matchPattern, rootID, nodeID,
  4320. resolverWithInitializedOnly, this);
  4321. // Wrap `xpathResolver` to pass `initializedOnly` through.
  4322. function resolverWithInitializedOnly(step, contextID, resolveAttributes) {
  4323. return this.xpathResolver.call(this, step, contextID, resolveAttributes, initializedOnly);
  4324. }
  4325. }
  4326. // -- xpathResolver ------------------------------------------------------------------------
  4327. /// Interpret the steps of an XPath expression being resolved. Use with
  4328. /// vwf.utility.xpath#resolve.
  4329. ///
  4330. /// @name module:vwf~xpathResolver
  4331. ///
  4332. /// @param {Object} step
  4333. /// @param {ID} contextID
  4334. /// @param {Boolean} [resolveAttributes]
  4335. /// @param {Boolean} [initializedOnly]
  4336. /// Interpret nodes that haven't completed initialization as though they don't have
  4337. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  4338. /// applications should never have access to uninitialized parts of the application graph.
  4339. ///
  4340. /// @returns {ID[]}
  4341. xpathResolver(step, contextID, resolveAttributes, initializedOnly) {
  4342. let self = this;
  4343. var resultIDs = [];
  4344. switch (step.axis) {
  4345. // case "preceding": // TODO
  4346. // case "preceding-sibling": // TODO
  4347. case "ancestor-or-self":
  4348. resultIDs.push(contextID);
  4349. Array.prototype.push.apply(resultIDs, this.ancestors(contextID, initializedOnly));
  4350. break;
  4351. case "ancestor":
  4352. Array.prototype.push.apply(resultIDs, this.ancestors(contextID, initializedOnly));
  4353. break;
  4354. case "parent":
  4355. var parentID = this.parent(contextID, initializedOnly);
  4356. parentID && resultIDs.push(parentID);
  4357. break;
  4358. case "self":
  4359. resultIDs.push(contextID);
  4360. break;
  4361. case "child":
  4362. Array.prototype.push.apply(resultIDs,
  4363. this.children(contextID, initializedOnly).filter(function (childID) {
  4364. return childID;
  4365. }, this)
  4366. );
  4367. break;
  4368. case "descendant":
  4369. Array.prototype.push.apply(resultIDs,
  4370. this.descendants(contextID, initializedOnly).filter(function (descendantID) {
  4371. return descendantID;
  4372. }, this)
  4373. );
  4374. break;
  4375. case "descendant-or-self":
  4376. resultIDs.push(contextID);
  4377. Array.prototype.push.apply(resultIDs,
  4378. this.descendants(contextID, initializedOnly).filter(function (descendantID) {
  4379. return descendantID;
  4380. }, this)
  4381. );
  4382. break;
  4383. // case "following-sibling": // TODO
  4384. // case "following": // TODO
  4385. case "attribute":
  4386. if (resolveAttributes) {
  4387. resultIDs.push("@" + contextID); // TODO: @?
  4388. }
  4389. break;
  4390. // n/a: case "namespace":
  4391. // n/a: break;
  4392. }
  4393. switch (step.kind) {
  4394. // Name test.
  4395. case undefined:
  4396. resultIDs = resultIDs.filter(function (resultID) {
  4397. if (resultID[0] != "@") { // TODO: @?
  4398. return self.xpathNodeMatchesStep.call(this, resultID, step.name);
  4399. } else {
  4400. return self.xpathPropertyMatchesStep.call(this, resultID.slice(1), step.name); // TODO: @?
  4401. }
  4402. }, this);
  4403. break;
  4404. // Element test.
  4405. case "element":
  4406. // Cases: kind(node,type)
  4407. // element()
  4408. // element(name)
  4409. // element(,type)
  4410. // element(name,type)
  4411. resultIDs = resultIDs.filter(function (resultID) {
  4412. return resultID[0] != "@" && self.xpathNodeMatchesStep.call(this, resultID, step.name, step.type); // TODO: @?
  4413. }, this);
  4414. break;
  4415. // Attribute test.
  4416. case "attribute":
  4417. resultIDs = resultIDs.filter(function (resultID) {
  4418. return resultID[0] == "@" && self.xpathPropertyMatchesStep.call(this, resultID.slice(1), step.name); // TODO: @?
  4419. }, this);
  4420. break;
  4421. // The `doc()` function for referencing globals outside the current tree.
  4422. // http://www.w3.org/TR/xpath-functions/#func-doc.
  4423. case "doc":
  4424. if (this.root(contextID, initializedOnly)) {
  4425. var globalID = this.global(step.name, initializedOnly);
  4426. resultIDs = globalID ? [globalID] : [];
  4427. } else {
  4428. resultIDs = [];
  4429. }
  4430. break;
  4431. // Any-kind test.
  4432. case "node":
  4433. break;
  4434. // Unimplemented test.
  4435. default:
  4436. resultIDs = [];
  4437. break;
  4438. }
  4439. return resultIDs;
  4440. }
  4441. // -- xpathNodeMatchesStep -----------------------------------------------------------------
  4442. /// Determine if a node matches a step of an XPath expression being resolved.
  4443. ///
  4444. /// @name module:vwf~xpathNodeMatchesStep
  4445. ///
  4446. /// @param {ID} nodeID
  4447. /// @param {String} [name]
  4448. /// @param {String} [type]
  4449. ///
  4450. /// @returns {Boolean}
  4451. xpathNodeMatchesStep(nodeID, name, type) {
  4452. if (name && this.name(nodeID) != name) {
  4453. return false;
  4454. }
  4455. var matches_type = !type || this.uri(nodeID) == type ||
  4456. this.prototypes(nodeID, true).some(function (prototypeID) {
  4457. return this.uri(prototypeID) == type;
  4458. }, this);
  4459. return matches_type;
  4460. }
  4461. // -- xpathPropertyMatchesStep -------------------------------------------------------------
  4462. /// Determine if a property matches a step of an XPath expression being resolved.
  4463. ///
  4464. /// @name module:vwf~xpathPropertyMatchesStep
  4465. ///
  4466. /// @param {ID} nodeID
  4467. /// @param {String} [name]
  4468. ///
  4469. /// @returns {Boolean}
  4470. xpathPropertyMatchesStep(nodeID, name) {
  4471. var properties = this.models.object.properties(nodeID);
  4472. if (name) {
  4473. return properties[name];
  4474. } else {
  4475. return Object.keys(properties).some(function (propertyName) {
  4476. return properties[propertyName];
  4477. }, this);
  4478. }
  4479. }
  4480. /// Merge two component descriptors into a single descriptor for a combined component. A
  4481. /// component created from the combined descriptor will behave in the same way as a
  4482. /// component created from `nodeDescriptor` that extends a component created from
  4483. /// `prototypeDescriptor`.
  4484. ///
  4485. /// Warning: this implementation modifies `prototypeDescriptor`.
  4486. ///
  4487. /// @name module:vwf~mergeDescriptors
  4488. ///
  4489. /// @param {Object} nodeDescriptor
  4490. /// A descriptor representing a node extending `prototypeDescriptor`.
  4491. /// @param {Object} prototypeDescriptor
  4492. /// A descriptor representing a prototype for `nodeDescriptor`.
  4493. // Limitations:
  4494. //
  4495. // - Doesn't merge children from the prototype with like-named children in the node.
  4496. // - Doesn't merge property setters and getters from the prototype when the node provides
  4497. // an initializing value.
  4498. // - Methods from the prototype descriptor are lost with no way to invoke them if the node
  4499. // overrides them.
  4500. // - Scripts from both the prototype and the node are retained, but if both define an
  4501. // `initialize` function, the node's `initialize` will overwrite `initialize` in
  4502. // the prototype.
  4503. // - The prototype doesn't carry its location with it, so relative paths will load with
  4504. // respect to the location of the node.
  4505. mergeDescriptors(nodeDescriptor, prototypeDescriptor) {
  4506. if (nodeDescriptor.implements) {
  4507. prototypeDescriptor.implements = (prototypeDescriptor.implements || []).
  4508. concat(nodeDescriptor.implements);
  4509. }
  4510. if (nodeDescriptor.source) {
  4511. prototypeDescriptor.source = nodeDescriptor.source;
  4512. prototypeDescriptor.type = nodeDescriptor.type;
  4513. }
  4514. if (nodeDescriptor.properties) {
  4515. prototypeDescriptor.properties = prototypeDescriptor.properties || {};
  4516. for (var propertyName in nodeDescriptor.properties) {
  4517. prototypeDescriptor.properties[propertyName] = nodeDescriptor.properties[propertyName];
  4518. }
  4519. }
  4520. if (nodeDescriptor.methods) {
  4521. prototypeDescriptor.methods = prototypeDescriptor.methods || {};
  4522. for (var methodName in nodeDescriptor.methods) {
  4523. prototypeDescriptor.methods[methodName] = nodeDescriptor.methods[methodName];
  4524. }
  4525. }
  4526. if (nodeDescriptor.events) {
  4527. prototypeDescriptor.events = prototypeDescriptor.events || {};
  4528. for (var eventName in nodeDescriptor.events) {
  4529. prototypeDescriptor.events[eventName] = nodeDescriptor.events[eventName];
  4530. }
  4531. }
  4532. if (nodeDescriptor.children) {
  4533. prototypeDescriptor.children = prototypeDescriptor.children || {};
  4534. for (var childName in nodeDescriptor.children) {
  4535. prototypeDescriptor.children[childName] = nodeDescriptor.children[childName];
  4536. }
  4537. }
  4538. if (nodeDescriptor.scripts) {
  4539. prototypeDescriptor.scripts = (prototypeDescriptor.scripts || []).
  4540. concat(nodeDescriptor.scripts);
  4541. }
  4542. return prototypeDescriptor;
  4543. }
  4544. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4545. /// enumerable, but not writable or configurable.
  4546. ///
  4547. /// @param value
  4548. /// A value to wrap in a descriptor.
  4549. ///
  4550. /// @returns
  4551. /// An {@link external:Object.defineProperty} descriptor.
  4552. enumerable(value) {
  4553. return {
  4554. value: value,
  4555. enumerable: true,
  4556. writable: false,
  4557. configurable: false,
  4558. };
  4559. }
  4560. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4561. /// enumerable and writable, but not configurable.
  4562. ///
  4563. /// @param value
  4564. /// A value to wrap in a descriptor.
  4565. ///
  4566. /// @returns
  4567. /// An {@link external:Object.defineProperty} descriptor.
  4568. writable(value) {
  4569. return {
  4570. value: value,
  4571. enumerable: true,
  4572. writable: true,
  4573. configurable: false,
  4574. };
  4575. }
  4576. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4577. /// enumerable, writable, and configurable.
  4578. ///
  4579. /// @param value
  4580. /// A value to wrap in a descriptor.
  4581. ///
  4582. /// @returns
  4583. /// An {@link external:Object.defineProperty} descriptor.
  4584. configurable(value) {
  4585. return {
  4586. value: value,
  4587. enumerable: true,
  4588. writable: true,
  4589. configurable: true,
  4590. };
  4591. }
  4592. async chooseConnection(data) {
  4593. if (this.isLuminary) {
  4594. return await this.luminary.connect(data) //use Luminary
  4595. } else {
  4596. return data //use Reflector
  4597. }
  4598. }
  4599. }
  4600. export {
  4601. VWF
  4602. }