vwf.js 239 KB

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