vwf.js 240 KB

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