vwf.js 238 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466
  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. if(this.behaviors(nodeID)){
  2659. this.behaviors(nodeID).reverse().concat(this.prototype(nodeID)).
  2660. some(function (prototypeID, prototypeIndex, prototypeArray) {
  2661. if (prototypeIndex < prototypeArray.length - 1) {
  2662. propertyValue = this.getProperty(prototypeID, propertyName, true); // behavior node only, not its prototypes
  2663. } else if (prototypeID !== this.kutility.protoNodeURI) {
  2664. propertyValue = this.getProperty(prototypeID, propertyName); // prototype node, recursively
  2665. }
  2666. return propertyValue !== undefined;
  2667. }, this);
  2668. }
  2669. }
  2670. // Call gotProperty() on each view.
  2671. this.views.forEach(function (view) {
  2672. view.gotProperty && view.gotProperty(nodeID, propertyName, propertyValue); // TODO: be sure this is the value actually gotten and not an intermediate value from above
  2673. });
  2674. }
  2675. // Clear the retrieval counter when the outermost `getProperty` completes.
  2676. if (outermost) {
  2677. delete entrants.retrievals;
  2678. }
  2679. this.logger.debugu();
  2680. return propertyValue;
  2681. }
  2682. // -- createMethod -------------------------------------------------------------------------
  2683. /// @name module:vwf.createMethod
  2684. ///
  2685. /// @see {@link module:vwf/api/kernel.createMethod}
  2686. createMethod(nodeID, methodName, methodParameters, methodBody) {
  2687. let self = this;
  2688. this.logger.debuggx("createMethod", function () {
  2689. return [nodeID, methodName, methodParameters, self.loggableScript(methodBody)];
  2690. });
  2691. var node = self.nodes.existing[nodeID];
  2692. // Register the method.
  2693. node.methods.create(methodName, node.initialized && node.patchable);
  2694. // Call `creatingMethod` on each model. The method is considered created after all
  2695. // models have run.
  2696. this.models.forEach(function (model) {
  2697. model.creatingMethod && model.creatingMethod(nodeID, methodName, methodParameters,
  2698. methodBody);
  2699. });
  2700. // Call `createdMethod` on each view. The view is being notified that a method has been
  2701. // created.
  2702. this.views.forEach(function (view) {
  2703. view.createdMethod && view.createdMethod(nodeID, methodName, methodParameters,
  2704. methodBody);
  2705. });
  2706. // Send the meta event into the application.
  2707. if (this.models.kernel.enabled()) {
  2708. this.fireEvent(nodeID, ["methods", "created"], [methodName]);
  2709. }
  2710. this.logger.debugu();
  2711. }
  2712. // -- setMethod ----------------------------------------------------------------------------
  2713. /// @name module:vwf.setMethod
  2714. ///
  2715. /// @see {@link module:vwf/api/kernel.setMethod}
  2716. setMethod(nodeID, methodName, methodHandler) {
  2717. let self = this;
  2718. this.logger.debuggx("setMethod", function () {
  2719. return [nodeID, methodName]; // TODO loggable methodHandler
  2720. });
  2721. var node = this.nodes.existing[nodeID];
  2722. methodHandler = this.normalizedHandler(methodHandler);
  2723. if (!node.methods.hasOwn(methodName)) {
  2724. // If the method doesn't exist on this node, delegate to `kernel.createMethod` to
  2725. // create and assign the method.
  2726. this.createMethod(nodeID, methodName, methodHandler.parameters, methodHandler.body); // TODO: result
  2727. } else {
  2728. // Call `settingMethod` on each model. The first model to return a non-undefined
  2729. // value dictates the return value.
  2730. this.models.some(function (model) {
  2731. // Call the driver.
  2732. var handler = model.settingMethod && model.settingMethod(nodeID, methodName, methodHandler);
  2733. // Update the value to the value assigned if the driver handled it.
  2734. if (handler !== undefined) {
  2735. methodHandler = self.utility.merge({}, handler); // omit `undefined` values
  2736. }
  2737. // Exit the iterator once a driver has handled the assignment.
  2738. return handler !== undefined;
  2739. });
  2740. // Record the change.
  2741. if (node.initialized && node.patchable) {
  2742. node.methods.change(methodName);
  2743. }
  2744. // Call `satMethod` on each view.
  2745. this.views.forEach(function (view) {
  2746. view.satMethod && view.satMethod(nodeID, methodName, methodHandler);
  2747. });
  2748. }
  2749. this.logger.debugu();
  2750. return methodHandler;
  2751. }
  2752. // -- getMethod ----------------------------------------------------------------------------
  2753. /// @name module:vwf.getMethod
  2754. ///
  2755. /// @see {@link module:vwf/api/kernel.getMethod}
  2756. getMethod(nodeID, methodName) {
  2757. let self = this;
  2758. this.logger.debuggx("getMethod", function () {
  2759. return [nodeID, methodName];
  2760. });
  2761. var node = this.nodes.existing[nodeID];
  2762. // Call `gettingMethod` on each model. The first model to return a non-undefined value
  2763. // dictates the return value.
  2764. var methodHandler = {};
  2765. this.models.some(function (model) {
  2766. // Call the driver.
  2767. var handler = model.gettingMethod && model.gettingMethod(nodeID, methodName);
  2768. // Update the value to the value assigned if the driver handled it.
  2769. if (handler !== undefined) {
  2770. methodHandler = self.utility.merge({}, handler); // omit `undefined` values
  2771. }
  2772. // Exit the iterator once a driver has handled the retrieval.
  2773. return handler !== undefined;
  2774. });
  2775. // Call `gotMethod` on each view.
  2776. this.views.forEach(function (view) {
  2777. view.gotMethod && view.gotMethod(nodeID, methodName, methodHandler);
  2778. });
  2779. this.logger.debugu();
  2780. return methodHandler;
  2781. }
  2782. // -- callMethod ---------------------------------------------------------------------------
  2783. /// @name module:vwf.callMethod
  2784. ///
  2785. /// @see {@link module:vwf/api/kernel.callMethod}
  2786. callMethod(nodeID, methodName, methodParameters) {
  2787. let self = this;
  2788. this.logger.debuggx("callMethod", function () {
  2789. return [nodeID, methodName, JSON.stringify(self.loggableValues(methodParameters))];
  2790. });
  2791. // Call callingMethod() on each model. The first model to return a non-undefined value
  2792. // dictates the return value.
  2793. var methodValue = undefined;
  2794. this.models.some(function (model) {
  2795. methodValue = model.callingMethod && model.callingMethod(nodeID, methodName, methodParameters);
  2796. return methodValue !== undefined;
  2797. });
  2798. // Call calledMethod() on each view.
  2799. this.views.forEach(function (view) {
  2800. view.calledMethod && view.calledMethod(nodeID, methodName, methodParameters, methodValue);
  2801. });
  2802. this.logger.debugu();
  2803. return methodValue;
  2804. }
  2805. // -- createEvent --------------------------------------------------------------------------
  2806. /// @name module:vwf.createEvent
  2807. ///
  2808. /// @see {@link module:vwf/api/kernel.createEvent}
  2809. 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
  2810. this.logger.debuggx("createEvent", nodeID, eventName, eventParameters);
  2811. var node = this.nodes.existing[nodeID];
  2812. // Encode any namespacing into the name. (Namespaced names were added in 0.6.21.)
  2813. var encodedEventName = this.namespaceEncodedName(eventName);
  2814. // Register the event.
  2815. node.events.create(encodedEventName, node.initialized && node.patchable, eventParameters);
  2816. // Call `creatingEvent` on each model. The event is considered created after all models
  2817. // have run.
  2818. this.models.forEach(function (model) {
  2819. model.creatingEvent && model.creatingEvent(nodeID, encodedEventName, eventParameters);
  2820. });
  2821. // Call `createdEvent` on each view. The view is being notified that a event has been
  2822. // created.
  2823. this.views.forEach(function (view) {
  2824. view.createdEvent && view.createdEvent(nodeID, encodedEventName, eventParameters);
  2825. });
  2826. // Send the meta event into the application.
  2827. if (this.models.kernel.enabled()) {
  2828. this.fireEvent(nodeID, ["events", "created"], [eventName]);
  2829. }
  2830. this.logger.debugu();
  2831. }
  2832. // -- setEvent -----------------------------------------------------------------------------
  2833. /// @name module:vwf.setEvent
  2834. ///
  2835. /// @see {@link module:vwf/api/kernel.setEvent}
  2836. setEvent(nodeID, eventName, eventDescriptor) {
  2837. this.logger.debuggx("setEvent", function () {
  2838. return [nodeID, eventName]; // TODO: loggable eventDescriptor
  2839. });
  2840. var node = this.nodes.existing[nodeID];
  2841. // eventDescriptor = normalizedHandler( eventDescriptor ); // TODO
  2842. // Encode any namespacing into the name.
  2843. var encodedEventName = this.namespaceEncodedName(eventName);
  2844. if (!node.events.hasOwn(encodedEventName)) {
  2845. // If the event doesn't exist on this node, delegate to `kernel.createEvent` to
  2846. // create and assign the event.
  2847. this.createEvent(nodeID, eventName, eventDescriptor.parameters); // TODO: result
  2848. (eventDescriptor.listeners || []).forEach(function (listener) {
  2849. return this.addEventListener(nodeID, eventName, listener, listener.context, listener.phases);
  2850. }, this);
  2851. } else {
  2852. // Locate the event in the registry.
  2853. var event = node.events.existing[encodedEventName];
  2854. // xxx
  2855. eventDescriptor = {
  2856. parameters: event.parameters ?
  2857. event.parameters.slice() : [], // TODO: note: we're ignoring eventDescriptor.parameters in the set
  2858. listeners: (eventDescriptor.listeners || []).map(function (listener) {
  2859. if (event.listeners.hasOwn(listener.id)) {
  2860. return this.setEventListener(nodeID, eventName, listener.id, listener);
  2861. } else {
  2862. return this.addEventListener(nodeID, eventName, listener, listener.context, listener.phases);
  2863. }
  2864. }, this),
  2865. };
  2866. }
  2867. this.logger.debugu();
  2868. return eventDescriptor;
  2869. }
  2870. // -- getEvent -----------------------------------------------------------------------------
  2871. /// @name module:vwf.getEvent
  2872. ///
  2873. /// @see {@link module:vwf/api/kernel.getEvent}
  2874. getEvent(nodeID, eventName) {
  2875. this.logger.debuggx("getEvent", function () {
  2876. return [nodeID, eventName];
  2877. });
  2878. var node = this.nodes.existing[nodeID];
  2879. // Encode any namespacing into the name.
  2880. var encodedEventName = this.namespaceEncodedName(eventName);
  2881. // Locate the event in the registry.
  2882. var event = node.events.existing[encodedEventName];
  2883. // Build the result descriptor. Omit the `parameters` and `listeners` fields when the
  2884. // parameters or listeners are missing or empty, respectively.
  2885. var eventDescriptor = {};
  2886. if (event.parameters) {
  2887. eventDescriptor.parameters = event.parameters.slice();
  2888. }
  2889. if (event.listeners.existing.length) {
  2890. eventDescriptor.listeners = event.listeners.existing.map(function (eventListenerID) {
  2891. var listener = this.getEventListener(nodeID, eventName, eventListenerID);
  2892. listener.id = eventListenerID;
  2893. return listener;
  2894. }, this);
  2895. }
  2896. this.logger.debugu();
  2897. return eventDescriptor;
  2898. }
  2899. // -- addEventListener ---------------------------------------------------------------------
  2900. /// @name module:vwf.addEventListener
  2901. ///
  2902. /// @see {@link module:vwf/api/kernel.addEventListener}
  2903. addEventListener(nodeID, eventName, eventHandler, eventContextID, eventPhases) {
  2904. let self = this;
  2905. this.logger.debuggx("addEventListener", function () {
  2906. return [nodeID, eventName, self.loggableScript(eventHandler),
  2907. eventContextID, eventPhases
  2908. ];
  2909. });
  2910. var node = self.nodes.existing[nodeID];
  2911. // Encode any namespacing into the name.
  2912. var encodedEventName = this.namespaceEncodedName(eventName);
  2913. // Register the event if this is the first listener added to an event on a prototype.
  2914. if (!node.events.hasOwn(encodedEventName)) {
  2915. node.events.create(encodedEventName, node.initialized && node.patchable);
  2916. }
  2917. // Locate the event in the registry.
  2918. var event = node.events.existing[encodedEventName];
  2919. // Normalize the descriptor.
  2920. eventHandler = this.normalizedHandler(eventHandler, event.parameters);
  2921. // Register the listener.
  2922. var eventListenerID = eventHandler.id || this.sequence(nodeID);
  2923. event.listeners.create(eventListenerID, node.initialized && node.patchable);
  2924. // Call `addingEventListener` on each model.
  2925. this.models.forEach(function (model) {
  2926. model.addingEventListener &&
  2927. model.addingEventListener(nodeID, encodedEventName, eventListenerID,
  2928. eventHandler, eventContextID, eventPhases);
  2929. });
  2930. // Call `addedEventListener` on each view.
  2931. this.views.forEach(function (view) {
  2932. view.addedEventListener &&
  2933. view.addedEventListener(nodeID, encodedEventName, eventListenerID,
  2934. eventHandler, eventContextID, eventPhases);
  2935. });
  2936. this.logger.debugu();
  2937. return eventListenerID;
  2938. }
  2939. // -- removeEventListener ------------------------------------------------------------------
  2940. /// @name module:vwf.removeEventListener
  2941. ///
  2942. /// @see {@link module:vwf/api/kernel.removeEventListener}
  2943. removeEventListener(nodeID, eventName, eventListenerID) {
  2944. let self = this;
  2945. this.logger.debuggx("removeEventListener", function () {
  2946. return [nodeID, eventName, self.loggableScript(eventListenerID)];
  2947. });
  2948. var node = this.nodes.existing[nodeID];
  2949. // Encode any namespacing into the name.
  2950. var encodedEventName = this.namespaceEncodedName(eventName);
  2951. // Locate the event in the registry.
  2952. var event = node.events.existing[encodedEventName];
  2953. // Unregister the listener.
  2954. event.listeners.delete(eventListenerID, node.initialized && node.patchable);
  2955. // Call `removingEventListener` on each model.
  2956. this.models.forEach(function (model) {
  2957. model.removingEventListener &&
  2958. model.removingEventListener(nodeID, encodedEventName, eventListenerID);
  2959. });
  2960. // Call `removedEventListener` on each view.
  2961. this.views.forEach(function (view) {
  2962. view.removedEventListener &&
  2963. view.removedEventListener(nodeID, encodedEventName, eventListenerID);
  2964. });
  2965. this.logger.debugu();
  2966. return eventListenerID;
  2967. }
  2968. // -- setEventListener ---------------------------------------------------------------------
  2969. /// @name module:vwf.setEventListener
  2970. ///
  2971. /// @see {@link module:vwf/api/kernel.setEventListener}
  2972. setEventListener(nodeID, eventName, eventListenerID, eventListener) {
  2973. let self = this;
  2974. this.logger.debuggx("setEventListener", function () {
  2975. return [nodeID, eventName, eventListenerID]; // TODO: loggable eventListener
  2976. });
  2977. var node = this.nodes.existing[nodeID];
  2978. // Encode any namespacing into the name.
  2979. var encodedEventName = this.namespaceEncodedName(eventName);
  2980. // Locate the event in the registry.
  2981. var event = node.events.existing[encodedEventName];
  2982. // Normalize the descriptor.
  2983. eventListener = this.normalizedHandler(eventListener, event.parameters);
  2984. // Record the change.
  2985. if (node.initialized && node.patchable) {
  2986. event.listeners.change(eventListenerID);
  2987. }
  2988. // Call `settingEventListener` on each model. The first model to return a non-undefined
  2989. // value dictates the return value.
  2990. this.models.some(function (model) {
  2991. // Call the driver.
  2992. var listener = model.settingEventListener &&
  2993. model.settingEventListener(nodeID, encodedEventName, eventListenerID, eventListener);
  2994. // Update the value to the value assigned if the driver handled it.
  2995. if (listener !== undefined) {
  2996. eventListener = self.utility.merge({}, listener); // omit `undefined` values
  2997. }
  2998. // Exit the iterator once a driver has handled the assignment.
  2999. return listener !== undefined;
  3000. });
  3001. // Call `satEventListener` on each view.
  3002. this.views.forEach(function (view) {
  3003. view.satEventListener &&
  3004. view.satEventListener(nodeID, encodedEventName, eventListenerID, eventListener);
  3005. });
  3006. this.logger.debugu();
  3007. return eventListener;
  3008. }
  3009. // -- getEventListener ---------------------------------------------------------------------
  3010. /// @name module:vwf.getEventListener
  3011. ///
  3012. /// @see {@link module:vwf/api/kernel.getEventListener}
  3013. getEventListener(nodeID, eventName, eventListenerID) {
  3014. let self = this;
  3015. this.logger.debuggx("getEventListener", function () {
  3016. return [nodeID, eventName, eventListenerID];
  3017. });
  3018. // Encode any namespacing into the name.
  3019. var encodedEventName = this.namespaceEncodedName(eventName);
  3020. // Call `gettingEventListener` on each model. The first model to return a non-undefined
  3021. // value dictates the return value.
  3022. var eventListener = {};
  3023. this.models.some(function (model) {
  3024. // Call the driver.
  3025. var listener = model.gettingEventListener &&
  3026. model.gettingEventListener(nodeID, encodedEventName, eventListenerID);
  3027. // Update the value to the value assigned if the driver handled it.
  3028. if (listener !== undefined) {
  3029. eventListener = self.utility.merge({}, listener); // omit `undefined` values
  3030. }
  3031. // Exit the iterator once a driver has handled the assignment.
  3032. return listener !== undefined;
  3033. });
  3034. // Call `gotEventListener` on each view.
  3035. this.views.forEach(function (view) {
  3036. view.gotEventListener &&
  3037. view.gotEventListener(nodeID, encodedEventName, eventListenerID, eventListener);
  3038. });
  3039. this.logger.debugu();
  3040. return eventListener;
  3041. }
  3042. // -- flushEventListeners ------------------------------------------------------------------
  3043. /// @name module:vwf.flushEventListeners
  3044. ///
  3045. /// @see {@link module:vwf/api/kernel.flushEventListeners}
  3046. flushEventListeners(nodeID, eventName, eventContextID) {
  3047. this.logger.debuggx("flushEventListeners", nodeID, eventName, eventContextID);
  3048. // Encode any namespacing into the name.
  3049. var encodedEventName = this.namespaceEncodedName(eventName);
  3050. // Retrieve the event in case we need to remove listeners from it
  3051. var node = this.nodes.existing[nodeID];
  3052. var event = node.events.existing[encodedEventName];
  3053. // Call `flushingEventListeners` on each model.
  3054. this.models.forEach(function (model) {
  3055. var removedIds = model.flushingEventListeners &&
  3056. model.flushingEventListeners(nodeID, encodedEventName, eventContextID);
  3057. // If the model driver returned an array of the ids of event listeners that it
  3058. // removed, remove their references in the kernel
  3059. if (removedIds && removedIds.length) {
  3060. // Unregister the listeners that were flushed
  3061. removedIds.forEach(function (removedId) {
  3062. event.listeners.delete(removedId, node.initialized && node.patchable);
  3063. });
  3064. }
  3065. });
  3066. // Call `flushedEventListeners` on each view.
  3067. this.views.forEach(function (view) {
  3068. view.flushedEventListeners &&
  3069. view.flushedEventListeners(nodeID, encodedEventName, eventContextID);
  3070. });
  3071. // TODO: `flushEventListeners` can be interpreted by the kernel now and handled with a
  3072. // `removeEventListener` call instead of separate `flushingEventListeners` and
  3073. // `flushedEventListeners` calls to the drivers.
  3074. this.logger.debugu();
  3075. }
  3076. // -- fireEvent ----------------------------------------------------------------------------
  3077. /// @name module:vwf.fireEvent
  3078. ///
  3079. /// @see {@link module:vwf/api/kernel.fireEvent}
  3080. fireEvent(nodeID, eventName, eventParameters) {
  3081. let self = this;
  3082. this.logger.debuggx("fireEvent", function () {
  3083. return [nodeID, eventName, JSON.stringify(self.loggableValues(eventParameters))];
  3084. });
  3085. // Encode any namespacing into the name. (Namespaced names were added in 0.6.21.)
  3086. var encodedEventName = this.namespaceEncodedName(eventName);
  3087. // Call `firingEvent` on each model.
  3088. var handled = this.models.reduce(function (handled, model) {
  3089. return model.firingEvent && model.firingEvent(nodeID, encodedEventName, eventParameters) || handled;
  3090. }, false);
  3091. // Call `firedEvent` on each view.
  3092. this.views.forEach(function (view) {
  3093. view.firedEvent && view.firedEvent(nodeID, encodedEventName, eventParameters);
  3094. });
  3095. this.logger.debugu();
  3096. // TODO: `fireEvent` needs to tell the drivers to invoke each listener individually
  3097. // now that listeners can be spread across multiple drivers.
  3098. return handled;
  3099. }
  3100. // -- dispatchEvent ------------------------------------------------------------------------
  3101. /// Dispatch an event toward a node. Using fireEvent(), capture (down) and bubble (up) along
  3102. /// the path from the global root to the node. Cancel when one of the handlers returns a
  3103. /// truthy value to indicate that it has handled the event.
  3104. ///
  3105. /// @name module:vwf.dispatchEvent
  3106. ///
  3107. /// @see {@link module:vwf/api/kernel.dispatchEvent}
  3108. dispatchEvent(nodeID, eventName, eventParameters, eventNodeParameters) {
  3109. let self = this;
  3110. this.logger.debuggx("dispatchEvent", function () {
  3111. return [nodeID, eventName, JSON.stringify(self.loggableValues(eventParameters)),
  3112. JSON.stringify(self.loggableIndexedValues(eventNodeParameters))
  3113. ];
  3114. });
  3115. // Defaults for the parameters to send with the events. Values from `eventParameters`
  3116. // are sent to each node. `eventNodeParameters` contains additional values to send to
  3117. // specific nodes.
  3118. eventParameters = eventParameters || [];
  3119. eventNodeParameters = eventNodeParameters || {};
  3120. // Find the inheritance path from the node to the root.
  3121. var ancestorIDs = this.ancestors(nodeID);
  3122. var lastAncestorID = "";
  3123. // Make space to record the parameters sent to each node. Parameters provided for upper
  3124. // nodes cascade down until another definition is found for a lower node. We'll remember
  3125. // these on the way down and replay them on the way back up.
  3126. var cascadedEventNodeParameters = {
  3127. "": eventNodeParameters[""] || [] // defaults come from the "" key in eventNodeParameters
  3128. };
  3129. // Parameters passed to the handlers are the concatention of the eventParameters array,
  3130. // the eventNodeParameters for the node (cascaded), and the phase.
  3131. var targetEventParameters = undefined;
  3132. var phase = undefined;
  3133. var handled = false;
  3134. // Capturing phase.
  3135. phase = "capture"; // only handlers tagged "capture" will be invoked
  3136. handled = handled || ancestorIDs.reverse().some(function (ancestorID) { // TODO: reverse updates the array in place every time and we'd rather not
  3137. cascadedEventNodeParameters[ancestorID] = eventNodeParameters[ancestorID] ||
  3138. cascadedEventNodeParameters[lastAncestorID];
  3139. lastAncestorID = ancestorID;
  3140. targetEventParameters =
  3141. eventParameters.concat(cascadedEventNodeParameters[ancestorID], phase);
  3142. 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
  3143. return this.fireEvent(ancestorID, eventName, targetEventParameters);
  3144. }, this);
  3145. // At target.
  3146. phase = undefined; // invoke all handlers
  3147. cascadedEventNodeParameters[nodeID] = eventNodeParameters[nodeID] ||
  3148. cascadedEventNodeParameters[lastAncestorID];
  3149. targetEventParameters =
  3150. eventParameters.concat(cascadedEventNodeParameters[nodeID], phase);
  3151. handled = handled || this.fireEvent(nodeID, eventName, targetEventParameters);
  3152. // Bubbling phase.
  3153. phase = undefined; // invoke all handlers
  3154. handled = handled || ancestorIDs.reverse().some(function (ancestorID) { // TODO: reverse updates the array in place every time and we'd rather not
  3155. targetEventParameters =
  3156. eventParameters.concat(cascadedEventNodeParameters[ancestorID], phase);
  3157. return this.fireEvent(ancestorID, eventName, targetEventParameters);
  3158. }, this);
  3159. this.logger.debugu();
  3160. }
  3161. // -- execute ------------------------------------------------------------------------------
  3162. /// @name module:vwf.execute
  3163. ///
  3164. /// @see {@link module:vwf/api/kernel.execute}
  3165. execute(nodeID, scriptText, scriptType, callback_async /* result */ ) {
  3166. let self = this;
  3167. this.logger.debuggx("execute", function () {
  3168. return [nodeID, self.loggableScript(scriptText), scriptType];
  3169. });
  3170. // Assume JavaScript if the type is not specified and the text is a string.
  3171. if (!scriptType && (typeof scriptText == "string" || scriptText instanceof String)) {
  3172. scriptType = "application/javascript";
  3173. }
  3174. // Call executing() on each model. The script is considered executed after all models
  3175. // have run.
  3176. var scriptValue = undefined;
  3177. // Watch for any async kernel calls generated as we execute the scriptText and wait for
  3178. // them to complete before calling the callback.
  3179. self.models.kernel.capturingAsyncs(function () {
  3180. self.models.some(function (model) {
  3181. scriptValue = model.executing &&
  3182. model.executing(nodeID, scriptText, scriptType);
  3183. return scriptValue !== undefined;
  3184. });
  3185. // Call executed() on each view to notify view that a script has been executed.
  3186. self.views.forEach(function (view) {
  3187. view.executed && view.executed(nodeID, scriptText, scriptType);
  3188. });
  3189. }, function () {
  3190. callback_async && callback_async(scriptValue);
  3191. });
  3192. this.logger.debugu();
  3193. return scriptValue;
  3194. }
  3195. // -- random -------------------------------------------------------------------------------
  3196. /// @name module:vwf.random
  3197. ///
  3198. /// @see {@link module:vwf/api/kernel.random}
  3199. random(nodeID) {
  3200. return this.models.object.random(nodeID);
  3201. }
  3202. // -- seed ---------------------------------------------------------------------------------
  3203. /// @name module:vwf.seed
  3204. ///
  3205. /// @see {@link module:vwf/api/kernel.seed}
  3206. seed(nodeID, seed) {
  3207. return this.models.object.seed(nodeID, seed);
  3208. }
  3209. // -- time ---------------------------------------------------------------------------------
  3210. /// The current simulation time.
  3211. ///
  3212. /// @name module:vwf.time
  3213. ///
  3214. /// @see {@link module:vwf/api/kernel.time}
  3215. now() {
  3216. return this.virtualTime.now;
  3217. }
  3218. time() {
  3219. return this.virtualTime.now;
  3220. }
  3221. // -- client -------------------------------------------------------------------------------
  3222. /// The moniker of the client responsible for the current action. Will be falsy for actions
  3223. /// originating in the server, such as time ticks.
  3224. ///
  3225. /// @name module:vwf.client
  3226. ///
  3227. /// @see {@link module:vwf/api/kernel.client}
  3228. client() {
  3229. return this.virtualTime.client_;
  3230. }
  3231. // -- moniker ------------------------------------------------------------------------------
  3232. /// The identifer the server assigned to this client.
  3233. ///
  3234. /// @name module:vwf.moniker
  3235. ///
  3236. /// @see {@link module:vwf/api/kernel.moniker}
  3237. moniker() {
  3238. return this.moniker_;
  3239. }
  3240. // -- application --------------------------------------------------------------------------
  3241. /// @name module:vwf.application
  3242. ///
  3243. /// @see {@link module:vwf/api/kernel.application}
  3244. application(initializedOnly) {
  3245. let self = this;
  3246. var applicationID;
  3247. Object.keys(self.nodes.globals).forEach(function (globalID) {
  3248. var global = self.nodes.existing[globalID];
  3249. if ((!initializedOnly || global.initialized) && global.name === "application") {
  3250. applicationID = globalID;
  3251. }
  3252. }, this);
  3253. return applicationID;
  3254. }
  3255. // -- intrinsics ---------------------------------------------------------------------------
  3256. /// @name module:vwf.intrinsics
  3257. ///
  3258. /// @see {@link module:vwf/api/kernel.intrinsics}
  3259. intrinsics(nodeID, result) {
  3260. return this.models.object.intrinsics(nodeID, result);
  3261. }
  3262. // -- uri ----------------------------------------------------------------------------------
  3263. /// @name module:vwf.uri
  3264. ///
  3265. /// @see {@link module:vwf/api/kernel.uri}
  3266. uri(nodeID, searchAncestors, initializedOnly) {
  3267. var uri = this.models.object.uri(nodeID);
  3268. if (searchAncestors) {
  3269. while (!uri && (nodeID = this.parent(nodeID, initializedOnly))) {
  3270. uri = this.models.object.uri(nodeID);
  3271. }
  3272. }
  3273. return uri;
  3274. }
  3275. // -- name ---------------------------------------------------------------------------------
  3276. /// @name module:vwf.name
  3277. ///
  3278. /// @see {@link module:vwf/api/kernel.name}
  3279. name(nodeID) {
  3280. return this.models.object.name(nodeID);
  3281. }
  3282. // -- prototype ----------------------------------------------------------------------------
  3283. /// @name module:vwf.prototype
  3284. ///
  3285. /// @see {@link module:vwf/api/kernel.prototype}
  3286. prototype(nodeID) {
  3287. return this.models.object.prototype(nodeID);
  3288. }
  3289. // -- prototypes ---------------------------------------------------------------------------
  3290. /// @name module:vwf.prototypes
  3291. ///
  3292. /// @see {@link module:vwf/api/kernel.prototypes}
  3293. prototypes(nodeID, includeBehaviors) {
  3294. var prototypes = [];
  3295. do {
  3296. // Add the current node's behaviors.
  3297. if (includeBehaviors) {
  3298. var b = [].concat(this.behaviors(nodeID));
  3299. Array.prototype.push.apply(prototypes, b.reverse());
  3300. }
  3301. // Get the next prototype.
  3302. nodeID = this.prototype(nodeID);
  3303. // Add the prototype.
  3304. if (nodeID) {
  3305. prototypes.push(nodeID);
  3306. }
  3307. } while (nodeID);
  3308. return prototypes;
  3309. }
  3310. // -- behaviors ----------------------------------------------------------------------------
  3311. /// @name module:vwf.behaviors
  3312. ///
  3313. /// @see {@link module:vwf/api/kernel.behaviors}
  3314. behaviors(nodeID) {
  3315. return this.models.object.behaviors(nodeID);
  3316. }
  3317. // -- globals ------------------------------------------------------------------------------
  3318. /// @name module:vwf.globals
  3319. ///
  3320. /// @see {@link module:vwf/api/kernel.globals}
  3321. globals(initializedOnly) {
  3322. let self = this;
  3323. var globals = {};
  3324. Object.keys(self.nodes.globals).forEach(function (globalID) {
  3325. if (!initializedOnly || self.nodes.existing[globalID].initialized) {
  3326. globals[globalID] = undefined;
  3327. }
  3328. }, this);
  3329. return globals;
  3330. }
  3331. // -- global -------------------------------------------------------------------------------
  3332. /// @name module:vwf.global
  3333. ///
  3334. /// @see {@link module:vwf/api/kernel.global}
  3335. global(globalReference, initializedOnly) {
  3336. let self = this;
  3337. var globals = this.globals(initializedOnly);
  3338. // Look for a global node whose URI matches `globalReference`. If there is no match by
  3339. // URI, then search again by name.
  3340. return matches("uri") || matches("name");
  3341. // Look for a global node where the field named by `field` matches `globalReference`.
  3342. function matches(field) {
  3343. var matchingID;
  3344. Object.keys(globals).some(function (globalID) {
  3345. if (self.nodes.existing[globalID][field] === globalReference) {
  3346. matchingID = globalID;
  3347. return true;
  3348. }
  3349. });
  3350. return matchingID;
  3351. }
  3352. }
  3353. // -- root ---------------------------------------------------------------------------------
  3354. /// @name module:vwf.root
  3355. ///
  3356. /// @see {@link module:vwf/api/kernel.root}
  3357. root(nodeID, initializedOnly) {
  3358. var rootID;
  3359. // Walk the ancestors to the top of the tree. Stop when we reach the pseudo-node at the
  3360. // global root, which unlike all other nodes has a falsy ID, or `undefined` if we could
  3361. // not reach the top because `initializedOnly` is set and we attempted to cross between
  3362. // nodes that have and have not completed initialization.
  3363. do {
  3364. rootID = nodeID;
  3365. nodeID = this.parent(nodeID, initializedOnly);
  3366. } while (nodeID);
  3367. // Return the root ID, or `undefined` when `initializedOnly` is set and the node can't
  3368. // see the root.
  3369. return nodeID === undefined ? undefined : rootID;
  3370. }
  3371. // -- ancestors ----------------------------------------------------------------------------
  3372. /// @name module:vwf.ancestors
  3373. ///
  3374. /// @see {@link module:vwf/api/kernel.ancestors}
  3375. ancestors(nodeID, initializedOnly) {
  3376. var ancestors = [];
  3377. nodeID = this.parent(nodeID, initializedOnly);
  3378. while (nodeID) {
  3379. ancestors.push(nodeID);
  3380. nodeID = this.parent(nodeID, initializedOnly);
  3381. }
  3382. return ancestors;
  3383. }
  3384. // -- parent -------------------------------------------------------------------------------
  3385. /// @name module:vwf.parent
  3386. ///
  3387. /// @see {@link module:vwf/api/kernel.parent}
  3388. parent(nodeID, initializedOnly) {
  3389. return this.models.object.parent(nodeID, initializedOnly);
  3390. }
  3391. // -- children -----------------------------------------------------------------------------
  3392. /// @name module:vwf.children
  3393. ///
  3394. /// @see {@link module:vwf/api/kernel.children}
  3395. children(nodeID, initializedOnly) {
  3396. if (nodeID === undefined) {
  3397. this.logger.errorx("children", "cannot retrieve children of nonexistent node");
  3398. return;
  3399. }
  3400. return this.models.object.children(nodeID, initializedOnly);
  3401. }
  3402. // -- child --------------------------------------------------------------------------------
  3403. /// @name module:vwf.child
  3404. ///
  3405. /// @see {@link module:vwf/api/kernel.child}
  3406. child(nodeID, childReference, initializedOnly) {
  3407. var children = this.children(nodeID, initializedOnly);
  3408. if (typeof childReference === "number" || childReference instanceof Number) {
  3409. return children[childReference];
  3410. } else {
  3411. return children.filter(function (childID) {
  3412. return childID && this.name(childID) === childReference;
  3413. }, this)[0];
  3414. }
  3415. }
  3416. // -- descendants --------------------------------------------------------------------------
  3417. /// @name module:vwf.descendants
  3418. ///
  3419. /// @see {@link module:vwf/api/kernel.descendants}
  3420. descendants(nodeID, initializedOnly) {
  3421. if (nodeID === undefined) {
  3422. this.logger.errorx("descendants", "cannot retrieve children of nonexistent node");
  3423. return;
  3424. }
  3425. var descendants = [];
  3426. this.children(nodeID, initializedOnly).forEach(function (childID) {
  3427. descendants.push(childID);
  3428. childID && Array.prototype.push.apply(descendants, this.descendants(childID, initializedOnly));
  3429. }, this);
  3430. return descendants;
  3431. }
  3432. // -- sequence -----------------------------------------------------------------------------
  3433. /// @name module:vwf.sequence
  3434. ///
  3435. /// @see {@link module:vwf/api/kernel.sequence}
  3436. sequence(nodeID) {
  3437. return this.models.object.sequence(nodeID);
  3438. }
  3439. /// Locate nodes matching a search pattern. See vwf.api.kernel#find for details.
  3440. ///
  3441. /// @name module:vwf.find
  3442. ///
  3443. /// @param {ID} nodeID
  3444. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3445. /// is ignored for absolute patterns.
  3446. /// @param {String} matchPattern
  3447. /// The search pattern.
  3448. /// @param {Boolean} [initializedOnly]
  3449. /// Interpret nodes that haven't completed initialization as though they don't have
  3450. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3451. /// applications should never have access to uninitialized parts of the application graph.
  3452. /// @param {Function} [callback]
  3453. /// A callback to receive the search results. If callback is provided, find invokes
  3454. /// callback( matchID ) for each match. Otherwise the result is returned as an array.
  3455. ///
  3456. /// @returns {ID[]|undefined}
  3457. /// If callback is provided, undefined; otherwise an array of the node ids of the result.
  3458. ///
  3459. /// @see {@link module:vwf/api/kernel.find}
  3460. find(nodeID, matchPattern, initializedOnly, callback /* ( matchID ) */ ) {
  3461. // Interpret `find( nodeID, matchPattern, callback )` as
  3462. // `find( nodeID, matchPattern, undefined, callback )`. (`initializedOnly` was added in
  3463. // 0.6.8.)
  3464. if (typeof initializedOnly == "function" || initializedOnly instanceof Function) {
  3465. callback = initializedOnly;
  3466. initializedOnly = undefined;
  3467. }
  3468. // Run the query.
  3469. var matchIDs = find.call(this, nodeID, matchPattern, initializedOnly);
  3470. // Return the result. Invoke the callback if one was provided. Otherwise, return the
  3471. // array directly.
  3472. if (callback) {
  3473. matchIDs.forEach(function (matchID) {
  3474. callback(matchID);
  3475. });
  3476. } else { // TODO: future iterator proxy
  3477. return matchIDs;
  3478. }
  3479. }
  3480. // -- findClients ------------------------------------------------------------------------------
  3481. /// Locate client nodes matching a search pattern.
  3482. ///
  3483. /// @name module:vwf.findClients
  3484. ///
  3485. /// @param {ID} nodeID
  3486. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3487. /// is ignored for absolute patterns.
  3488. /// @param {String} matchPattern
  3489. /// The search pattern.
  3490. /// @param {Function} [callback]
  3491. /// A callback to receive the search results. If callback is provided, find invokes
  3492. /// callback( matchID ) for each match. Otherwise the result is returned as an array.
  3493. ///
  3494. /// @returns {ID[]|undefined}
  3495. /// If callback is provided, undefined; otherwise an array of the node ids of the result.
  3496. ///
  3497. /// @deprecated in version 0.6.21. Instead of `kernel.findClients( reference, "/pattern" )`,
  3498. /// use `kernel.find( reference, "doc('http://vwf.example.com/clients.vwf')/pattern" )`.
  3499. ///
  3500. /// @see {@link module:vwf/api/kernel.findClients}
  3501. findClients(nodeID, matchPattern, callback /* ( matchID ) */ ) {
  3502. this.logger.warn("`kernel.findClients` is deprecated. Use " +
  3503. "`kernel.find( nodeID, \"doc('proxy/clients.vwf')/pattern\" )`" +
  3504. " instead.");
  3505. var clientsMatchPattern = "doc('proxy/clients.vwf')" +
  3506. (matchPattern[0] === "/" ? "" : "/") + matchPattern;
  3507. return this.find(nodeID || this.application(), clientsMatchPattern, callback);
  3508. }
  3509. /// Test a node against a search pattern. See vwf.api.kernel#test for details.
  3510. ///
  3511. /// @name module:vwf.test
  3512. ///
  3513. /// @param {ID} nodeID
  3514. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3515. /// is ignored for absolute patterns.
  3516. /// @param {String} matchPattern
  3517. /// The search pattern.
  3518. /// @param {ID} testID
  3519. /// A node to test against the pattern.
  3520. /// @param {Boolean} [initializedOnly]
  3521. /// Interpret nodes that haven't completed initialization as though they don't have
  3522. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3523. /// applications should never have access to uninitialized parts of the application graph.
  3524. ///
  3525. /// @returns {Boolean}
  3526. /// true when testID matches the pattern.
  3527. ///
  3528. /// @see {@link module:vwf/api/kernel.test}
  3529. test(nodeID, matchPattern, testID, initializedOnly) {
  3530. // Run the query.
  3531. var matchIDs = this.find.call(this, nodeID, matchPattern, initializedOnly);
  3532. // Search for the test node in the result.
  3533. return matchIDs.some(function (matchID) {
  3534. return matchID == testID;
  3535. });
  3536. }
  3537. // == Private functions ====================================================================
  3538. // -- loadComponent ------------------------------------------------------------------------
  3539. /// @name module:vwf~loadComponent
  3540. loadComponent(nodeURI, baseURI, callback_async /* nodeDescriptor */ , errback_async /* errorMessage */ ) { // TODO: turn this into a generic xhr loader exposed as a kernel function?
  3541. let self = this;
  3542. if (nodeURI == self.kutility.protoNodeURI) {
  3543. callback_async(self.kutility.protoNodeDescriptor);
  3544. } else if (nodeURI.match(RegExp("^data:application/json;base64,"))) {
  3545. // Primarly for testing, parse one specific form of data URIs. We need to parse
  3546. // these ourselves since Chrome can't load data URIs due to cross origin
  3547. // restrictions.
  3548. callback_async(JSON.parse(atob(nodeURI.substring(29)))); // TODO: support all data URIs
  3549. } else {
  3550. self.virtualTime.suspend("while loading " + nodeURI); // suspend the queue
  3551. let fetchUrl = self.remappedURI(nodeURI, baseURI);
  3552. let dbName = fetchUrl.split(".").join("_");
  3553. const parseComp = function (f) {
  3554. let result = JSON.parse(f);
  3555. let nativeObject = result;
  3556. // console.log(nativeObject);
  3557. if (nativeObject) {
  3558. callback_async(nativeObject);
  3559. self.virtualTime.resume("after loading " + nodeURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3560. } else {
  3561. self.logger.warnx("loadComponent", "error loading", nodeURI + ":", error);
  3562. errback_async(error);
  3563. self.virtualTime.resume("after loading " + nodeURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3564. }
  3565. }
  3566. //var fileName = "";
  3567. // let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  3568. if (dbName.includes("proxy")) {
  3569. //userDB = await window._LCS_SYS_USER.get('proxy').then();
  3570. let proxyDB = self.proxy ? _LCSDB.user(self.proxy) : _LCSDB.user(_LCS_WORLD_USER.pub);
  3571. let fileName = dbName + '_json';
  3572. let dbNode = proxyDB.get('proxy').get(fileName);
  3573. let nodeProm = new Promise(res => dbNode.once(res));
  3574. nodeProm.then(comp => {
  3575. parseComp(comp);
  3576. })
  3577. // (function(r){
  3578. // //console.log(r);
  3579. // parseComp(r);
  3580. // });
  3581. } else {
  3582. let worldName = dbName.split('/')[1];
  3583. let fileName = dbName.split('/')[2] + '_json';
  3584. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').path(worldName).get(fileName);
  3585. let nodeProm = new Promise(res => dbNode.once(res))
  3586. nodeProm.then(comp => {
  3587. parseComp(comp);
  3588. })
  3589. // (function(r){
  3590. // //console.log(r);
  3591. // parseComp(r);
  3592. // });
  3593. }
  3594. //console.log(source);
  3595. //userDB.get(fileName).once(async function(res) {
  3596. // }, {wait: 1000})
  3597. }
  3598. }
  3599. // -- loadScript ---------------------------------------------------------------------------
  3600. /// @name module:vwf~loadScript
  3601. loadScript(scriptURI, baseURI, callback_async /* scriptText */ , errback_async /* errorMessage */ ) {
  3602. let self = this;
  3603. if (scriptURI.match(RegExp("^data:application/javascript;base64,"))) {
  3604. // Primarly for testing, parse one specific form of data URIs. We need to parse
  3605. // these ourselves since Chrome can't load data URIs due to cross origin
  3606. // restrictions.
  3607. callback_async(atob(scriptURI.substring(35))); // TODO: support all data URIs
  3608. } else {
  3609. self.virtualTime.suspend("while loading " + scriptURI); // suspend the queue
  3610. let fetchUrl = self.remappedURI(scriptURI, baseURI);
  3611. let dbName = fetchUrl.split(".").join("_")
  3612. const parseComp = function (res) {
  3613. let scriptText = res;
  3614. try {
  3615. callback_async(scriptText);
  3616. self.virtualTime.resume("after loading " + scriptURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3617. } catch (e) {
  3618. self.logger.warnx("loadScript", "error loading", scriptURI + ":", error);
  3619. errback_async(error);
  3620. self.virtualTime.resume("after loading " + scriptURI); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3621. }
  3622. }
  3623. let worldName = dbName.split('/')[1];
  3624. //let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  3625. if (dbName.includes("proxy")) {
  3626. let proxyDB = self.proxy ? _LCSDB.user(self.proxy) : _LCSDB.user(_LCS_WORLD_USER.pub);
  3627. //userDB = window._LCS_SYS_USER.get('proxy');
  3628. let fileName = dbName;
  3629. let dbNode = proxyDB.get('proxy').get(fileName);
  3630. let nodeProm = new Promise(res => dbNode.once(res))
  3631. nodeProm.then(comp => {
  3632. parseComp(comp);
  3633. })
  3634. // window._LCS_SYS_USER.get('proxy').get(fileName).get('file').once(function(r){
  3635. // //console.log(r);
  3636. // parseComp(r);
  3637. // });
  3638. } else {
  3639. let fileName = dbName.split('/')[2]; //dbName.replace(worldName + '/', "");
  3640. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').path(worldName).get(fileName);
  3641. let nodeProm = new Promise(res => dbNode.once(res))
  3642. nodeProm.then(comp => {
  3643. parseComp(comp);
  3644. })
  3645. // userDB.get('worlds').path(worldName).get(fileName).get('file').once(function(r){
  3646. // //console.log(r);
  3647. // parseComp(r);
  3648. // });
  3649. }
  3650. // userDB.get(fileName).once(, {wait: 1000})
  3651. }
  3652. }
  3653. /// Determine if a given property of a node has a setter function, either directly on the
  3654. /// node or inherited from a prototype.
  3655. ///
  3656. /// This function must run as a method of the kernel. Invoke as: nodePropertyHasSetter.call(
  3657. /// kernel, nodeID, propertyName ).
  3658. ///
  3659. /// @name module:vwf~nodePropertyHasSetter
  3660. ///
  3661. /// @param {ID} nodeID
  3662. /// @param {String} propertyName
  3663. ///
  3664. /// @returns {Boolean}
  3665. 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
  3666. var node = this.models.javascript.nodes[nodeID];
  3667. var setter = node.private.setters && node.private.setters[propertyName];
  3668. return typeof setter == "function" || setter instanceof Function;
  3669. }
  3670. /// Determine if a given property of a node has a setter function. The node's prototypes are
  3671. /// not considered.
  3672. ///
  3673. /// This function must run as a method of the kernel. Invoke as:
  3674. /// nodePropertyHasOwnSetter.call( kernel, nodeID, propertyName ).
  3675. ///
  3676. /// @name module:vwf~nodePropertyHasOwnSetter
  3677. ///
  3678. /// @param {ID} nodeID
  3679. /// @param {String} propertyName
  3680. ///
  3681. /// @returns {Boolean}
  3682. 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
  3683. var node = this.models.javascript.nodes[nodeID];
  3684. var setter = node.private.setters && node.private.setters.hasOwnProperty(propertyName) && node.private.setters[propertyName];
  3685. return typeof setter == "function" || setter instanceof Function;
  3686. }
  3687. /// Determine if a node has a child with the given name, either directly on the node or
  3688. /// inherited from a prototype.
  3689. ///
  3690. /// This function must run as a method of the kernel. Invoke as: nodeHasChild.call(
  3691. /// kernel, nodeID, childName ).
  3692. ///
  3693. /// @name module:vwf~nodeHasChild
  3694. ///
  3695. /// @param {ID} nodeID
  3696. /// @param {String} childName
  3697. ///
  3698. /// @returns {Boolean}
  3699. nodeHasChild(nodeID, childName) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript
  3700. var node = this.models.javascript.nodes[nodeID];
  3701. return childName in node.children;
  3702. }
  3703. /// Determine if a node has a child with the given name. The node's prototypes are not
  3704. /// considered.
  3705. ///
  3706. /// This function must run as a method of the kernel. Invoke as: nodeHasOwnChild.call(
  3707. /// kernel, nodeID, childName ).
  3708. ///
  3709. /// @name module:vwf~nodeHasOwnChild
  3710. ///
  3711. /// @param {ID} nodeID
  3712. /// @param {String} childName
  3713. ///
  3714. /// @returns {Boolean}
  3715. nodeHasOwnChild(nodeID, childName) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript
  3716. var node = this.models.javascript.nodes[nodeID];
  3717. var hasChild = false;
  3718. if (parseInt(childName).toString() !== childName) {
  3719. hasChild = node.children.hasOwnProperty(childName); // TODO: this is peeking inside of vwf-model-javascript
  3720. } else {
  3721. // Children with numeric names do not get added as properties of the children array, so loop over the children
  3722. // to check manually
  3723. for (var i = 0, il = node.children.length; i < il; i++) {
  3724. if (childName === node.children[i].name) {
  3725. hasChild = true;
  3726. }
  3727. }
  3728. }
  3729. return hasChild;
  3730. }
  3731. /// Determine if a component specifier is a URI.
  3732. ///
  3733. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3734. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3735. ///
  3736. /// @name module:vwf~componentIsURI
  3737. ///
  3738. /// @param {String|Object} candidate
  3739. ///
  3740. /// @returns {Boolean}
  3741. componentIsURI(candidate) {
  3742. return (typeof candidate == "string" || candidate instanceof String) && !this.componentIsID(candidate);
  3743. }
  3744. /// Determine if a component specifier is a descriptor.
  3745. ///
  3746. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3747. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3748. ///
  3749. /// @name module:vwf~componentIsDescriptor
  3750. ///
  3751. /// @param {String|Object} candidate
  3752. ///
  3753. /// @returns {Boolean}
  3754. componentIsDescriptor(candidate) {
  3755. return typeof candidate == "object" && candidate != null && !this.isPrimitive(candidate);
  3756. }
  3757. /// Determine if a component specifier is an ID.
  3758. ///
  3759. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3760. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3761. ///
  3762. /// @name module:vwf~componentIsID
  3763. ///
  3764. /// @param {String|Object} candidate
  3765. ///
  3766. /// @returns {Boolean}
  3767. componentIsID(candidate) {
  3768. return this.isPrimitive(candidate) && this.models.object.exists(candidate) &&
  3769. !(this.components[candidate] instanceof Array);
  3770. }
  3771. /// Determine if a value is a JavaScript primitive, or the boxed version of a JavaScript
  3772. /// primitive.
  3773. ///
  3774. /// Node IDs are JavaScript primitives. This function may be used to determine if a value
  3775. /// has the correct type to be a node ID.
  3776. ///
  3777. /// @name module:vwf~isPrimitive
  3778. ///
  3779. /// @param candidate
  3780. ///
  3781. /// @returns {Boolean}
  3782. isPrimitive(candidate) {
  3783. switch (typeof candidate) {
  3784. case "string":
  3785. case "number":
  3786. case "boolean":
  3787. return true;
  3788. case "object":
  3789. return candidate instanceof String || candidate instanceof Number ||
  3790. candidate instanceof Boolean;
  3791. default:
  3792. return false;
  3793. }
  3794. }
  3795. /// Determine if an object is a component descriptor. Detect the type by searching for
  3796. /// descriptor keys in the candidate object.
  3797. ///
  3798. /// @name module:vwf~objectIsComponent
  3799. ///
  3800. /// @param {Object} candidate
  3801. ///
  3802. /// @returns {Boolean}
  3803. objectIsComponent(candidate) {
  3804. var componentAttributes = [
  3805. "extends",
  3806. "implements",
  3807. "source",
  3808. "type",
  3809. "properties",
  3810. "methods",
  3811. "events",
  3812. "children",
  3813. "scripts",
  3814. ];
  3815. var isComponent = false;
  3816. if (typeof candidate == "object" && candidate != null) {
  3817. isComponent = componentAttributes.some(function (attributeName) {
  3818. return candidate.hasOwnProperty(attributeName);
  3819. });
  3820. }
  3821. return isComponent;
  3822. }
  3823. /// Determine if a property initializer is a detailed initializer containing explicit
  3824. /// accessor and value parameters (rather than a simple value specification). Detect the
  3825. /// type by searching for property initializer keys in the candidate object.
  3826. ///
  3827. /// @name module:vwf~valueHasAccessors
  3828. ///
  3829. /// @param {Object} candidate
  3830. ///
  3831. /// @returns {Boolean}
  3832. valueHasAccessors(candidate) {
  3833. var accessorAttributes = [
  3834. "get",
  3835. "set",
  3836. "value",
  3837. "node",
  3838. "create",
  3839. "undefined",
  3840. ];
  3841. var hasAccessors = false;
  3842. if (typeof candidate == "object" && candidate != null) {
  3843. hasAccessors = accessorAttributes.some(function (attributeName) {
  3844. return candidate.hasOwnProperty(attributeName);
  3845. });
  3846. }
  3847. return hasAccessors;
  3848. }
  3849. /// Determine if a method or event initializer is a detailed initializer containing a
  3850. /// parameter list along with the body text (method initializers only). Detect the type by
  3851. /// searching for method and event initializer keys in the candidate object.
  3852. ///
  3853. /// @name module:vwf~valueHasBody
  3854. ///
  3855. /// @param {Object} candidate
  3856. ///
  3857. /// @returns {Boolean}
  3858. 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
  3859. var bodyAttributes = [
  3860. "parameters",
  3861. "body",
  3862. "listeners",
  3863. ];
  3864. var hasBody = false; // TODO: "body" term is confusing, but that's the current terminology used in vwf/model/javascript
  3865. if (typeof candidate == "object" && candidate != null) {
  3866. hasBody = bodyAttributes.some(function (attributeName) {
  3867. return candidate.hasOwnProperty(attributeName);
  3868. });
  3869. }
  3870. return hasBody;
  3871. }
  3872. /// Determine if a script initializer is a detailed initializer containing explicit text and
  3873. /// type parameters (rather than being a simple text specification). Detect the type by
  3874. /// searching for the script initializer keys in the candidate object.
  3875. ///
  3876. /// @name module:vwf~valueHasType
  3877. ///
  3878. /// @param {Object} candidate
  3879. ///
  3880. /// @returns {Boolean}
  3881. valueHasType(candidate) { // TODO: refactor and share with valueHasBody, valueHasAccessors and possibly objectIsComponent
  3882. var typeAttributes = [
  3883. "source",
  3884. "text",
  3885. "type",
  3886. ];
  3887. var hasType = false;
  3888. if (typeof candidate == "object" && candidate != null) {
  3889. hasType = typeAttributes.some(function (attributeName) {
  3890. return candidate.hasOwnProperty(attributeName);
  3891. });
  3892. }
  3893. return hasType;
  3894. }
  3895. /// Convert a potentially-namespaced member name into a string such that a namespaced name
  3896. /// will be distinct from an encoded name in any other namespace, or from any simple name
  3897. /// not having a namespace.
  3898. ///
  3899. /// Simple names are strings such as `"name"`. Namespaced names are arrays of strings, such
  3900. /// as `[ "ns", "name" ]` or `[ "outer", "inner", "name" ]`. An array containing a single
  3901. /// string, such as `[ "name" ]`, is not namespaced and is the same name as `"name"`.
  3902. ///
  3903. /// Each of the following encodes into a distinct value:
  3904. ///
  3905. /// `"name"` or `[ "name" ]`
  3906. /// `[ "a", "name" ]`
  3907. /// `[ "b", "name" ]`
  3908. /// `[ "a", "a", "name" ]`
  3909. /// `[ "a", "b", "name" ]`
  3910. /// `[ "b", "b", "name" ]`
  3911. /// *etc.*
  3912. ///
  3913. /// @name module:vwf~namespaceEncodedName
  3914. ///
  3915. /// @param {String|String[]} memberName
  3916. /// A string, or an array of strings containing a name preceded by any number of namespace
  3917. /// names. In an array, each element defines a unique space for the member name and for
  3918. /// any intermediate namespaces.
  3919. ///
  3920. /// @returns {String}
  3921. namespaceEncodedName(memberName) {
  3922. if (typeof memberName === "object" && memberName instanceof Array) {
  3923. return (memberName.length !== 1) ? "vwf$" + memberName.join("$") : memberName[0];
  3924. } else {
  3925. return memberName;
  3926. }
  3927. }
  3928. /// Convert a (potentially-abbreviated) component specification to a descriptor parsable by
  3929. /// vwf.createChild. The following forms are accepted:
  3930. ///
  3931. /// - Descriptor: { extends: component, source: ..., type: ..., ... }
  3932. /// - Component URI: http://host/path/to/component.vwf
  3933. /// - Asset URI: http://host/ath/to/asset.type
  3934. /// - Node ID
  3935. ///
  3936. /// They are converted as follows:
  3937. ///
  3938. /// - Descriptor: unchanged [1]
  3939. /// - Component URI: a component that extends the component identified by the URI
  3940. /// - Asset URI: a component having the asset identified by the URI as its source
  3941. /// - Node ID: a component that extends the previously-created node identified by the ID
  3942. ///
  3943. /// [1] As a special case, missing MIME types are filled in for assets matcching the
  3944. /// patterns *.unity3d and *.dae, and components having assets of those types but no
  3945. /// prototype declared will be upgraded to extend scene.vwf and navscene.vwf, respectively.
  3946. ///
  3947. /// @name module:vwf~normalizedComponent
  3948. ///
  3949. /// @param {String|Object} component
  3950. ///
  3951. /// @returns {Object}
  3952. normalizedComponent(component) {
  3953. // Convert a component URI to an instance of that type or an asset reference to an
  3954. // untyped reference to that asset. Convert a component ID to an instance of that
  3955. // prototype.
  3956. if (this.componentIsURI(component)) {
  3957. if (component.match(/\.vwf$/)) { // TODO: detect component from mime-type instead of extension?
  3958. component = {
  3959. extends: component
  3960. };
  3961. } else {
  3962. component = {
  3963. source: component
  3964. };
  3965. }
  3966. } else if (this.componentIsID(component)) {
  3967. component = {
  3968. extends: component
  3969. };
  3970. }
  3971. // Fill in the mime type from the source specification if not provided.
  3972. if (component.source && !component.type) { // TODO: validate component
  3973. 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)
  3974. if (match) {
  3975. switch (match[1]) {
  3976. case "unity3d":
  3977. component.type = "application/vnd.unity";
  3978. break;
  3979. case "dae":
  3980. component.type = "model/vnd.collada+xml";
  3981. break;
  3982. }
  3983. }
  3984. }
  3985. // Fill in the component type from the mime type if not provided.
  3986. if (component.type && !component.extends) { // TODO: load from a server configuration file
  3987. switch (component.type) {
  3988. case "application/vnd.unity":
  3989. component.extends = "http://vwf.example.com/scene.vwf";
  3990. break;
  3991. case "model/vnd.collada+xml":
  3992. component.extends = "http://vwf.example.com/navscene.vwf";
  3993. break;
  3994. }
  3995. }
  3996. return component;
  3997. }
  3998. /// Convert a `Handler` specification into the standard form of an object containing
  3999. /// `parameters`, `body` and `type` fields.
  4000. ///
  4001. /// @name module:vwf~normalizedHandler
  4002. ///
  4003. /// @param {Handler|string}
  4004. /// @param {string[]} [defaultParameters]
  4005. ///
  4006. /// @returns {Handler}
  4007. normalizedHandler(handler, defaultParameters) {
  4008. // Convert abbreviated forms to the explict `Handler` form.
  4009. if (typeof handler !== "object" || handler instanceof Array) {
  4010. handler = {
  4011. body: handler
  4012. }; //if (require("vwf/configuration").active["preserve-script-closures"]
  4013. } else if (this.configuration["preserve-script-closures"] && (typeof handler == "function" || handler instanceof Function)) {
  4014. handler = {
  4015. body: handler
  4016. };
  4017. }
  4018. // Use a default parameter list if the handler doesn't provide its own and if defaults
  4019. // were provided.
  4020. if (!handler.parameters && defaultParameters) {
  4021. handler.parameters = defaultParameters;
  4022. }
  4023. // Fill in a default media type if `type` is not provided. A `body` of type `string` is
  4024. // taken to be `application/javascript`.
  4025. if (handler.type === undefined) {
  4026. if (typeof handler.body === "string" || handler.body instanceof String) {
  4027. handler.type = "application/javascript";
  4028. }
  4029. }
  4030. return handler;
  4031. }
  4032. /// Convert a `fields` object as passed between the client and reflector and stored in the
  4033. /// message queue into a form suitable for writing to a log.
  4034. ///
  4035. /// @name module:vwf~loggableFields
  4036. ///
  4037. /// @param {Object} fields
  4038. ///
  4039. /// @returns {Object}
  4040. loggableFields(fields) {
  4041. return this.utility.transform(fields, this.utility.transforms.transit);
  4042. }
  4043. /// Convert a component URI, descriptor or ID into a form suitable for writing to a log.
  4044. ///
  4045. /// @name module:vwf~loggableComponent
  4046. ///
  4047. /// @param {String|Object} component
  4048. ///
  4049. /// @returns {String|Object}
  4050. loggableComponent(component) {
  4051. return this.utility.transform(component, this.loggableComponentTransformation);
  4052. }
  4053. /// Convert an arbitrary JavaScript value into a form suitable for writing to a log.
  4054. ///
  4055. /// @name module:vwf~loggableValue
  4056. ///
  4057. /// @param {Object} value
  4058. ///
  4059. /// @returns {Object}
  4060. loggableValue(value) {
  4061. let self = this;
  4062. return this.utility.transform(value, function (object, names, depth) {
  4063. object = self.utility.transforms.transit(object, names, depth);
  4064. return typeof object == "number" ? Number(object.toPrecision(5)) : object; // reduce numeric precision to remove visual noise
  4065. });
  4066. }
  4067. /// Convert an array of arbitrary JavaScript values into a form suitable for writing to a
  4068. /// log.
  4069. ///
  4070. /// @name module:vwf~loggableValues
  4071. ///
  4072. /// @param {Object[]|undefined} values
  4073. ///
  4074. /// @returns {Object[]|undefined}
  4075. loggableValues(values) {
  4076. return this.loggableValue(values);
  4077. }
  4078. /// Convert an object indexing arrays of arbitrary JavaScript values into a form suitable
  4079. /// for writing to a log.
  4080. ///
  4081. /// @name module:vwf~loggableIndexedValues
  4082. ///
  4083. /// @param {Object|undefined} values
  4084. ///
  4085. /// @returns {Object|undefined}
  4086. loggableIndexedValues(values) {
  4087. return this.loggableValue(values);
  4088. }
  4089. /// Convert script text into a form suitable for writing to a log.
  4090. ///
  4091. /// @name module:vwf~loggableScript
  4092. ///
  4093. /// @param {String|undefined} script
  4094. ///
  4095. /// @returns {String}
  4096. loggableScript(script) {
  4097. return (script || "").replace(/\s+/g, " ").substring(0, 100);
  4098. }
  4099. // -- remappedURI --------------------------------------------------------------------------
  4100. /// Remap a component URI to its location in a local cache.
  4101. ///
  4102. /// http://vwf.example.com/component.vwf => http://localhost/proxy/vwf.example.com/component.vwf
  4103. ///
  4104. /// @name module:vwf~remappedURI
  4105. remappedURI(uri, baseURI) {
  4106. // var match = uri.match( RegExp( "http://(vwf.example.com)/(.*)" ) );
  4107. // if ( match ) {
  4108. // uri = window.location.protocol + "//" + window.location.host +
  4109. // "/proxy/" + match[1] + "/" + match[2];
  4110. // }
  4111. if (baseURI && uri[0] !== "/") {
  4112. let newURI = "";
  4113. let parts = baseURI.split('/');
  4114. parts[parts.length - 1] = uri;
  4115. parts.map(el => {
  4116. newURI = newURI + el + '/';
  4117. })
  4118. return newURI.slice(0, -1)
  4119. }
  4120. return uri
  4121. }
  4122. // -- resolvedDescriptor -------------------------------------------------------------------
  4123. /// Resolve relative URIs in a component descriptor.
  4124. ///
  4125. /// @name module:vwf~resolvedDescriptor
  4126. resolvedDescriptor(component, baseURI) {
  4127. return this.utility.transform(component, resolvedDescriptorTransformationWithBaseURI);
  4128. function resolvedDescriptorTransformationWithBaseURI(object, names, depth) {
  4129. return resolvedDescriptorTransformation.call(this, object, names, depth, baseURI);
  4130. }
  4131. }
  4132. // -- loggableComponentTransformation ------------------------------------------------------
  4133. /// vwf/utility/transform() transformation function to truncate the verbose bits of a
  4134. /// component so that it may be written to a log.
  4135. ///
  4136. /// @name module:vwf~loggableComponentTransformation
  4137. loggableComponentTransformation(object, names, depth) {
  4138. // Get our bearings at the current recusion level.
  4139. var markers = this.descriptorMarkers(object, names, depth);
  4140. // Transform the object here.
  4141. switch (markers.containerName) {
  4142. case "extends":
  4143. // Omit a component descriptor for the prototype.
  4144. if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {
  4145. return {};
  4146. }
  4147. break;
  4148. case "implements":
  4149. // Omit component descriptors for the behaviors.
  4150. if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {
  4151. return {};
  4152. }
  4153. break;
  4154. case "properties":
  4155. // Convert property values to a loggable version, and omit getter and setter
  4156. // text.
  4157. if (markers.memberIndex == 0 && !this.valueHasAccessors(object) ||
  4158. markers.memberIndex == 1 && names[0] == "value") {
  4159. return this.loggableValue(object);
  4160. } else if (markers.memberIndex == 1 && (names[0] == "get" || names[0] == "set")) {
  4161. return "...";
  4162. }
  4163. break;
  4164. case "methods":
  4165. // Omit method body text.
  4166. if (markers.memberIndex == 0 && !this.valueHasBody(object) ||
  4167. markers.memberIndex == 1 && names[0] == "body") {
  4168. return "...";
  4169. }
  4170. break;
  4171. case "events":
  4172. // Nothing for events.
  4173. break;
  4174. case "children":
  4175. // Omit child component descriptors.
  4176. if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {
  4177. return {};
  4178. }
  4179. break;
  4180. case "scripts":
  4181. // Shorten script text.
  4182. if (markers.memberIndex == 0 && !this.valueHasType(object) ||
  4183. markers.memberIndex == 1 && names[0] == "text") {
  4184. return "...";
  4185. }
  4186. break;
  4187. }
  4188. return object;
  4189. }
  4190. // -- resolvedDescriptorTransformation -----------------------------------------------------
  4191. /// vwf/utility/transform() transformation function to resolve relative URIs in a component
  4192. /// descriptor.
  4193. ///
  4194. /// @name module:vwf~resolvedDescriptorTransformation
  4195. resolvedDescriptorTransformation(object, names, depth, baseURI) {
  4196. // Get our bearings at the current recusion level.
  4197. var markers = this.descriptorMarkers(object, names, depth);
  4198. // Resolve all the URIs.
  4199. switch (markers.containerName) {
  4200. case "extends":
  4201. case "implements":
  4202. case "source":
  4203. case "children":
  4204. if (markers.memberIndex == 0 && this.componentIsURI(object)) {
  4205. return object //require( "vwf/utility" ).resolveURI( object, baseURI );
  4206. }
  4207. break;
  4208. case "scripts":
  4209. if (markers.memberIndex == 1 && names[0] == "source") {
  4210. return object //require( "vwf/utility" ).resolveURI( object, baseURI );
  4211. }
  4212. break;
  4213. }
  4214. return object;
  4215. }
  4216. // -- descriptorMarkers --------------------------------------------------------------------
  4217. /// Locate the closest container (`properties`, `methods`, `events`, `children`) and
  4218. /// contained member in a `vwf/utility/transform` iterator call on a component descriptor.
  4219. ///
  4220. /// @name module:vwf~descriptorMarkers
  4221. descriptorMarkers(object, names, depth) {
  4222. // Find the index of the lowest nested component in the names list.
  4223. var componentIndex = names.length;
  4224. while (componentIndex > 2 && names[componentIndex - 1] == "children") {
  4225. componentIndex -= 2;
  4226. }
  4227. // depth names notes
  4228. // ----- ----- -----
  4229. // 0: [] the component
  4230. // 1: [ "properties" ] its properties object
  4231. // 2: [ "propertyName", "properties" ] one property
  4232. // 1: [ "children" ] the children object
  4233. // 2: [ "childName", "children" ] one child
  4234. // 3: [ "properties", "childName", "children" ] the child's properties
  4235. // 4: [ "propertyName", "properties", "childName", "children" ] one child property
  4236. if (componentIndex > 0) {
  4237. // Locate the container ("properties", "methods", "events", etc.) below the
  4238. // component in the names list.
  4239. var containerIndex = componentIndex - 1;
  4240. var containerName = names[containerIndex];
  4241. // Locate the member as appropriate for the container.
  4242. if (containerName == "extends") {
  4243. var memberIndex = containerIndex;
  4244. var memberName = names[memberIndex];
  4245. } else if (containerName == "implements") {
  4246. if (containerIndex > 0) {
  4247. if (typeof names[containerIndex - 1] == "number") {
  4248. var memberIndex = containerIndex - 1;
  4249. var memberName = names[memberIndex];
  4250. } else {
  4251. var memberIndex = containerIndex;
  4252. var memberName = undefined;
  4253. }
  4254. } else if (typeof object != "object" || !(object instanceof Array)) {
  4255. var memberIndex = containerIndex;
  4256. var memberName = undefined;
  4257. }
  4258. } else if (containerName == "source" || containerName == "type") {
  4259. var memberIndex = containerIndex;
  4260. var memberName = names[memberIndex];
  4261. } else if (containerName == "properties" || containerName == "methods" || containerName == "events" ||
  4262. containerName == "children") {
  4263. if (containerIndex > 0) {
  4264. var memberIndex = containerIndex - 1;
  4265. var memberName = names[memberIndex];
  4266. }
  4267. } else if (containerName == "scripts") {
  4268. if (containerIndex > 0) {
  4269. if (typeof names[containerIndex - 1] == "number") {
  4270. var memberIndex = containerIndex - 1;
  4271. var memberName = names[memberIndex];
  4272. } else {
  4273. var memberIndex = containerIndex;
  4274. var memberName = undefined;
  4275. }
  4276. } else if (typeof object != "object" || !(object instanceof Array)) {
  4277. var memberIndex = containerIndex;
  4278. var memberName = undefined;
  4279. }
  4280. } else {
  4281. containerIndex = undefined;
  4282. containerName = undefined;
  4283. }
  4284. }
  4285. return {
  4286. containerIndex: containerIndex,
  4287. containerName: containerName,
  4288. memberIndex: memberIndex,
  4289. memberName: memberName,
  4290. };
  4291. }
  4292. /// Locate nodes matching a search pattern. {@link module:vwf/api/kernel.find} describes the
  4293. /// supported patterns.
  4294. ///
  4295. /// This is the internal implementation used by {@link module:vwf.find} and
  4296. /// {@link module:vwf.test}.
  4297. ///
  4298. /// This function must run as a method of the kernel. Invoke it as:
  4299. /// `find.call( kernel, nodeID, matchPattern, initializedOnly )`.
  4300. ///
  4301. /// @name module:vwf~find
  4302. ///
  4303. /// @param {ID} nodeID
  4304. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  4305. /// is ignored for absolute patterns.
  4306. /// @param {String} matchPattern
  4307. /// The search pattern.
  4308. /// @param {Boolean} [initializedOnly]
  4309. /// Interpret nodes that haven't completed initialization as though they don't have
  4310. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  4311. /// applications should never have access to uninitialized parts of the application graph.
  4312. ///
  4313. /// @returns {ID[]|undefined}
  4314. /// An array of the node ids of the result.
  4315. find(nodeID, matchPattern, initializedOnly) {
  4316. // Evaluate the expression using the provided node as the reference. Take the root node
  4317. // to be the root of the reference node's tree. If a reference node is not provided, use
  4318. // the application as the root.
  4319. var rootID = nodeID ? this.root(nodeID, initializedOnly) :
  4320. this.application(initializedOnly);
  4321. return this.xpath.resolve(matchPattern, rootID, nodeID,
  4322. resolverWithInitializedOnly, this);
  4323. // Wrap `xpathResolver` to pass `initializedOnly` through.
  4324. function resolverWithInitializedOnly(step, contextID, resolveAttributes) {
  4325. return this.xpathResolver.call(this, step, contextID, resolveAttributes, initializedOnly);
  4326. }
  4327. }
  4328. // -- xpathResolver ------------------------------------------------------------------------
  4329. /// Interpret the steps of an XPath expression being resolved. Use with
  4330. /// vwf.utility.xpath#resolve.
  4331. ///
  4332. /// @name module:vwf~xpathResolver
  4333. ///
  4334. /// @param {Object} step
  4335. /// @param {ID} contextID
  4336. /// @param {Boolean} [resolveAttributes]
  4337. /// @param {Boolean} [initializedOnly]
  4338. /// Interpret nodes that haven't completed initialization as though they don't have
  4339. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  4340. /// applications should never have access to uninitialized parts of the application graph.
  4341. ///
  4342. /// @returns {ID[]}
  4343. xpathResolver(step, contextID, resolveAttributes, initializedOnly) {
  4344. let self = this;
  4345. var resultIDs = [];
  4346. switch (step.axis) {
  4347. // case "preceding": // TODO
  4348. // case "preceding-sibling": // TODO
  4349. case "ancestor-or-self":
  4350. resultIDs.push(contextID);
  4351. Array.prototype.push.apply(resultIDs, this.ancestors(contextID, initializedOnly));
  4352. break;
  4353. case "ancestor":
  4354. Array.prototype.push.apply(resultIDs, this.ancestors(contextID, initializedOnly));
  4355. break;
  4356. case "parent":
  4357. var parentID = this.parent(contextID, initializedOnly);
  4358. parentID && resultIDs.push(parentID);
  4359. break;
  4360. case "self":
  4361. resultIDs.push(contextID);
  4362. break;
  4363. case "child":
  4364. Array.prototype.push.apply(resultIDs,
  4365. this.children(contextID, initializedOnly).filter(function (childID) {
  4366. return childID;
  4367. }, this)
  4368. );
  4369. break;
  4370. case "descendant":
  4371. Array.prototype.push.apply(resultIDs,
  4372. this.descendants(contextID, initializedOnly).filter(function (descendantID) {
  4373. return descendantID;
  4374. }, this)
  4375. );
  4376. break;
  4377. case "descendant-or-self":
  4378. resultIDs.push(contextID);
  4379. Array.prototype.push.apply(resultIDs,
  4380. this.descendants(contextID, initializedOnly).filter(function (descendantID) {
  4381. return descendantID;
  4382. }, this)
  4383. );
  4384. break;
  4385. // case "following-sibling": // TODO
  4386. // case "following": // TODO
  4387. case "attribute":
  4388. if (resolveAttributes) {
  4389. resultIDs.push("@" + contextID); // TODO: @?
  4390. }
  4391. break;
  4392. // n/a: case "namespace":
  4393. // n/a: break;
  4394. }
  4395. switch (step.kind) {
  4396. // Name test.
  4397. case undefined:
  4398. resultIDs = resultIDs.filter(function (resultID) {
  4399. if (resultID[0] != "@") { // TODO: @?
  4400. return self.xpathNodeMatchesStep.call(this, resultID, step.name);
  4401. } else {
  4402. return self.xpathPropertyMatchesStep.call(this, resultID.slice(1), step.name); // TODO: @?
  4403. }
  4404. }, this);
  4405. break;
  4406. // Element test.
  4407. case "element":
  4408. // Cases: kind(node,type)
  4409. // element()
  4410. // element(name)
  4411. // element(,type)
  4412. // element(name,type)
  4413. resultIDs = resultIDs.filter(function (resultID) {
  4414. return resultID[0] != "@" && self.xpathNodeMatchesStep.call(this, resultID, step.name, step.type); // TODO: @?
  4415. }, this);
  4416. break;
  4417. // Attribute test.
  4418. case "attribute":
  4419. resultIDs = resultIDs.filter(function (resultID) {
  4420. return resultID[0] == "@" && self.xpathPropertyMatchesStep.call(this, resultID.slice(1), step.name); // TODO: @?
  4421. }, this);
  4422. break;
  4423. // The `doc()` function for referencing globals outside the current tree.
  4424. // http://www.w3.org/TR/xpath-functions/#func-doc.
  4425. case "doc":
  4426. if (this.root(contextID, initializedOnly)) {
  4427. var globalID = this.global(step.name, initializedOnly);
  4428. resultIDs = globalID ? [globalID] : [];
  4429. } else {
  4430. resultIDs = [];
  4431. }
  4432. break;
  4433. // Any-kind test.
  4434. case "node":
  4435. break;
  4436. // Unimplemented test.
  4437. default:
  4438. resultIDs = [];
  4439. break;
  4440. }
  4441. return resultIDs;
  4442. }
  4443. // -- xpathNodeMatchesStep -----------------------------------------------------------------
  4444. /// Determine if a node matches a step of an XPath expression being resolved.
  4445. ///
  4446. /// @name module:vwf~xpathNodeMatchesStep
  4447. ///
  4448. /// @param {ID} nodeID
  4449. /// @param {String} [name]
  4450. /// @param {String} [type]
  4451. ///
  4452. /// @returns {Boolean}
  4453. xpathNodeMatchesStep(nodeID, name, type) {
  4454. if (name && this.name(nodeID) != name) {
  4455. return false;
  4456. }
  4457. var matches_type = !type || this.uri(nodeID) == type ||
  4458. this.prototypes(nodeID, true).some(function (prototypeID) {
  4459. return this.uri(prototypeID) == type;
  4460. }, this);
  4461. return matches_type;
  4462. }
  4463. // -- xpathPropertyMatchesStep -------------------------------------------------------------
  4464. /// Determine if a property matches a step of an XPath expression being resolved.
  4465. ///
  4466. /// @name module:vwf~xpathPropertyMatchesStep
  4467. ///
  4468. /// @param {ID} nodeID
  4469. /// @param {String} [name]
  4470. ///
  4471. /// @returns {Boolean}
  4472. xpathPropertyMatchesStep(nodeID, name) {
  4473. var properties = this.models.object.properties(nodeID);
  4474. if (name) {
  4475. return properties[name];
  4476. } else {
  4477. return Object.keys(properties).some(function (propertyName) {
  4478. return properties[propertyName];
  4479. }, this);
  4480. }
  4481. }
  4482. /// Merge two component descriptors into a single descriptor for a combined component. A
  4483. /// component created from the combined descriptor will behave in the same way as a
  4484. /// component created from `nodeDescriptor` that extends a component created from
  4485. /// `prototypeDescriptor`.
  4486. ///
  4487. /// Warning: this implementation modifies `prototypeDescriptor`.
  4488. ///
  4489. /// @name module:vwf~mergeDescriptors
  4490. ///
  4491. /// @param {Object} nodeDescriptor
  4492. /// A descriptor representing a node extending `prototypeDescriptor`.
  4493. /// @param {Object} prototypeDescriptor
  4494. /// A descriptor representing a prototype for `nodeDescriptor`.
  4495. // Limitations:
  4496. //
  4497. // - Doesn't merge children from the prototype with like-named children in the node.
  4498. // - Doesn't merge property setters and getters from the prototype when the node provides
  4499. // an initializing value.
  4500. // - Methods from the prototype descriptor are lost with no way to invoke them if the node
  4501. // overrides them.
  4502. // - Scripts from both the prototype and the node are retained, but if both define an
  4503. // `initialize` function, the node's `initialize` will overwrite `initialize` in
  4504. // the prototype.
  4505. // - The prototype doesn't carry its location with it, so relative paths will load with
  4506. // respect to the location of the node.
  4507. mergeDescriptors(nodeDescriptor, prototypeDescriptor) {
  4508. if (nodeDescriptor.implements) {
  4509. prototypeDescriptor.implements = (prototypeDescriptor.implements || []).
  4510. concat(nodeDescriptor.implements);
  4511. }
  4512. if (nodeDescriptor.source) {
  4513. prototypeDescriptor.source = nodeDescriptor.source;
  4514. prototypeDescriptor.type = nodeDescriptor.type;
  4515. }
  4516. if (nodeDescriptor.properties) {
  4517. prototypeDescriptor.properties = prototypeDescriptor.properties || {};
  4518. for (var propertyName in nodeDescriptor.properties) {
  4519. prototypeDescriptor.properties[propertyName] = nodeDescriptor.properties[propertyName];
  4520. }
  4521. }
  4522. if (nodeDescriptor.methods) {
  4523. prototypeDescriptor.methods = prototypeDescriptor.methods || {};
  4524. for (var methodName in nodeDescriptor.methods) {
  4525. prototypeDescriptor.methods[methodName] = nodeDescriptor.methods[methodName];
  4526. }
  4527. }
  4528. if (nodeDescriptor.events) {
  4529. prototypeDescriptor.events = prototypeDescriptor.events || {};
  4530. for (var eventName in nodeDescriptor.events) {
  4531. prototypeDescriptor.events[eventName] = nodeDescriptor.events[eventName];
  4532. }
  4533. }
  4534. if (nodeDescriptor.children) {
  4535. prototypeDescriptor.children = prototypeDescriptor.children || {};
  4536. for (var childName in nodeDescriptor.children) {
  4537. prototypeDescriptor.children[childName] = nodeDescriptor.children[childName];
  4538. }
  4539. }
  4540. if (nodeDescriptor.scripts) {
  4541. prototypeDescriptor.scripts = (prototypeDescriptor.scripts || []).
  4542. concat(nodeDescriptor.scripts);
  4543. }
  4544. return prototypeDescriptor;
  4545. }
  4546. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4547. /// enumerable, but not writable or configurable.
  4548. ///
  4549. /// @param value
  4550. /// A value to wrap in a descriptor.
  4551. ///
  4552. /// @returns
  4553. /// An {@link external:Object.defineProperty} descriptor.
  4554. enumerable(value) {
  4555. return {
  4556. value: value,
  4557. enumerable: true,
  4558. writable: false,
  4559. configurable: false,
  4560. };
  4561. }
  4562. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4563. /// enumerable and writable, but not configurable.
  4564. ///
  4565. /// @param value
  4566. /// A value to wrap in a descriptor.
  4567. ///
  4568. /// @returns
  4569. /// An {@link external:Object.defineProperty} descriptor.
  4570. writable(value) {
  4571. return {
  4572. value: value,
  4573. enumerable: true,
  4574. writable: true,
  4575. configurable: false,
  4576. };
  4577. }
  4578. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4579. /// enumerable, writable, and configurable.
  4580. ///
  4581. /// @param value
  4582. /// A value to wrap in a descriptor.
  4583. ///
  4584. /// @returns
  4585. /// An {@link external:Object.defineProperty} descriptor.
  4586. configurable(value) {
  4587. return {
  4588. value: value,
  4589. enumerable: true,
  4590. writable: true,
  4591. configurable: true,
  4592. };
  4593. }
  4594. async chooseConnection(data) {
  4595. if (this.isLuminary) {
  4596. return await this.luminary.connect(data) //use Luminary
  4597. } else {
  4598. return data //use Reflector
  4599. }
  4600. }
  4601. }
  4602. export {
  4603. VWF
  4604. }