javascript.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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. /// vwf/model/javascript.js is a placeholder for the JavaScript object interface to the
  7. /// simulation.
  8. ///
  9. /// @module vwf/model/javascript
  10. /// @requires vwf/model
  11. /// @requires vwf/kernel/utility
  12. /// @requires vwf/utility
  13. /// @requires vwf/configuration
  14. import { Utility } from "/core/vwf/utility/utility.js";
  15. import { KUtility } from "/core/vwf/utility/kutility.js";
  16. import { Fabric } from "/core/vwf/fabric.js";
  17. class VWFJavaScript extends Fabric {
  18. constructor(module) {
  19. console.log("JavaScript constructor");
  20. super(module, "Model")
  21. }
  22. factory() {
  23. let _self_ = this;
  24. return this.load(
  25. this.module,
  26. {
  27. // This is a placeholder for providing a natural integration between simulation and the
  28. // browser's JavaScript environment.
  29. //
  30. // Within the JavaScript environment, component instances appear as JavaScript objects.
  31. //
  32. // - Properties appear in the "properties" field. Each property contains a getter and
  33. // setter callback to notify the object of property manipulation.
  34. // - Methods appear in "methods".
  35. // - Events appear in "events".
  36. // - "parent" refers to the parent node and "children" is an array of the child nodes.
  37. //
  38. // - Node prototypes use the JavaScript prototype chain.
  39. // - Properties, methods, events, and children may be referenced directly on the node or
  40. // within their respective collections by name when there is no conflict with another
  41. // attribute.
  42. // - Properties support getters and setters that invoke a handler that may influence the
  43. // property access.
  44. // == Module Definition ====================================================================
  45. // -- initialize ---------------------------------------------------------------------------
  46. initialize: function() {
  47. this.nodes = {}; // maps id => new type()
  48. this.protoNode = undefined; // this.nodes[kutility.protoNodeURI] once it exists
  49. this.creatingNode( undefined, 0 ); // global root // TODO: to allow vwf.children( 0 ), vwf.getNode( 0 ); is this the best way, or should the kernel createNode( global-root-id /* 0 */ )?
  50. },
  51. // == Model API ============================================================================
  52. // -- creatingNode -------------------------------------------------------------------------
  53. creatingNode: function( nodeID, childID, childExtendsID, childImplementsIDs,
  54. childSource, childType, childIndex, childName, callback /* ( ready ) */ ) {
  55. var self = this;
  56. // Get the prototype node.
  57. var prototype = this.nodes[childExtendsID] || Object.prototype;
  58. // Get the behavior nodes.
  59. var behaviors = ( childImplementsIDs || [] ).map( function( childImplementsID ) {
  60. return self.nodes[childImplementsID];
  61. } );
  62. // For each behavior, create a proxy for this node to the behavior and attach it above
  63. // the prototype, or above the most recently-attached behavior.
  64. behaviors.forEach( function( behavior ) {
  65. prototype = VWFJavaScript.proxiedBehavior.call( self, prototype, behavior );
  66. } );
  67. // Create the node. Its prototype is the most recently-attached behavior, or the
  68. // specific prototype if no behaviors are attached.
  69. const handler = {
  70. get: function( obj, prop, receiver ) {
  71. if (prop in obj || prop == 'node') {
  72. return Reflect.get(obj, prop, receiver);
  73. }
  74. else {
  75. let ch = Reflect.get(obj, 'children', receiver);
  76. if(ch){
  77. let child = Object.values(ch).filter(el=>el['displayName'] == prop)[0];
  78. if (child){
  79. //console.log('TRAp children', child);
  80. return child
  81. }
  82. }
  83. }
  84. return undefined
  85. }
  86. }
  87. var node = this.nodes[childID] = new Proxy(Object.create( prototype ), handler);
  88. if ( childID === VWFJavaScript.kutility.protoNodeURI ) {
  89. this.protoNode = node;
  90. }
  91. Object.defineProperty( node, "private", {
  92. value: {} // for bookkeeping, not visible to scripts on the node // TODO: well, ideally not visible; hide this better ("_private", "vwf_private", ?)
  93. } );
  94. Object.defineProperty( node, "id", {
  95. value: childID,
  96. enumerable: true,
  97. } );
  98. Object.defineProperty( node, "protoID", {
  99. get: function() {
  100. return self.kernel.prototype( this.id );
  101. },
  102. enumerable: true,
  103. } );
  104. Object.defineProperty( node, "proto", {
  105. get: function() {
  106. let protoID = self.kernel.prototype( this.id )
  107. return self.nodes[ protoID ];
  108. },
  109. enumerable: true,
  110. } );
  111. Object.defineProperty( node, "uri", { // "this" is node
  112. get: function() {
  113. return self.kernel.uri( this.id );
  114. },
  115. enumerable: true,
  116. } );
  117. node.name = childName;
  118. node.parent = undefined;
  119. Object.defineProperty( node, "parent_", { // "this" is node in get/set
  120. get: function() {
  121. return this.parent;
  122. },
  123. set: function( value ) {
  124. var childIndex;
  125. if ( this.parent ) {
  126. var oldParent = this.parent;
  127. self.kernel.removeChild( this.parent.id, this.id );
  128. childIndex = oldParent.children.indexOf( this );
  129. if ( childIndex != -1 )
  130. oldParent.children.splice( childIndex, 1 );
  131. }
  132. self.kernel.addChild( value.id, this.id, this.name );
  133. this.parent = value;
  134. childIndex = this.parent.children.indexOf( this );
  135. if ( childIndex == -1 )
  136. this.parent.children.push( this );
  137. },
  138. } );
  139. node.source = childSource;
  140. node.type = childType;
  141. Object.defineProperty( node, "logger", {
  142. value: this.logger.for( "#" + ( childName || childIndex || childID ), node ),
  143. enumerable: true,
  144. } );
  145. // Properties.
  146. node.properties = Object.create( prototype.properties || Object.prototype, {
  147. node: { value: node } // for node.properties accessors (non-enumerable) // TODO: hide this better
  148. } );
  149. Object.defineProperty( node.properties, "create", {
  150. value: function( name, value, get, set ) { // "this" is node.properties
  151. return self.kernel.createProperty( this.node.id, name, value, get, set );
  152. }
  153. } );
  154. // Attach the property meta events to `node.properties.{created,initialized,deleted}`.
  155. VWFJavaScript.createEventAccessor.call( this, node.properties, "created", "properties" );
  156. VWFJavaScript.createEventAccessor.call( this, node.properties, "initialized", "properties" );
  157. VWFJavaScript.createEventAccessor.call( this, node.properties, "deleted", "properties" );
  158. node.private.getters = Object.create( prototype.private ?
  159. prototype.private.getters : Object.prototype
  160. );
  161. node.private.setters = Object.create( prototype.private ?
  162. prototype.private.setters : Object.prototype
  163. );
  164. // Methods.
  165. node.methods = Object.create( prototype.methods || Object.prototype, {
  166. node: { value: node } // for node.methods accessors (non-enumerable) // TODO: hide this better
  167. } );
  168. Object.defineProperty( node.methods, "create", {
  169. value: function( name, parameters, body ) { // "this" is node.methods // TODO: also accept create( name, body )
  170. return self.kernel.createMethod( this.node.id, name, parameters, body );
  171. }
  172. } );
  173. // Attach the method meta events to `node.methods.{created,deleted}`.
  174. VWFJavaScript.createEventAccessor.call( this, node.methods, "created", "methods" );
  175. VWFJavaScript.createEventAccessor.call( this, node.methods, "deleted", "methods" );
  176. node.private.bodies = Object.create( prototype.private ?
  177. prototype.private.bodies : Object.prototype
  178. );
  179. // Events.
  180. node.events = Object.create( prototype.events || Object.prototype, {
  181. node: { value: node }, // for node.events accessors (non-enumerable) // TODO: hide this better
  182. } );
  183. // TODO: these only need to be on the base node's events object
  184. Object.defineProperty( node.events, "create", {
  185. value: function( name, parameters ) { // "this" is node.events
  186. return self.kernel.createEvent( this.node.id, name, parameters );
  187. }
  188. } );
  189. // Attach the event meta events to `node.events.{created,deleted}`.
  190. VWFJavaScript.createEventAccessor.call( this, node.events, "created", "events" );
  191. VWFJavaScript.createEventAccessor.call( this, node.events, "deleted", "events" );
  192. // Provide helper functions to create the directives for adding, removing and flushing
  193. // event handlers.
  194. // Add: `node.events.*eventName* =
  195. // node.events.add( handler [, phases ] [, context ] [, callback( listenerID ) ] )`
  196. Object.defineProperty( node.events, "add", {
  197. value: function( handler, phases, context, callback /* listenerID */ ) {
  198. // Interpret `add( handler [, phases|context ], callback )` as
  199. // `add( handler, phases|context|undefined, undefined, callback )`.
  200. if ( typeof context === "function" || context instanceof Function ) {
  201. callback = context;
  202. context = undefined;
  203. } else if ( typeof phases === "function" || phases instanceof Function ) {
  204. callback = phases;
  205. context = phases = undefined;
  206. }
  207. // Interpret `add( handler, context, ... )` as `add( handler, undefined, context, ... )`.
  208. if ( VWFJavaScript.valueIsNode.call( self, phases ) ) {
  209. context = phases;
  210. phases = undefined;
  211. }
  212. return { add: true, handler: handler, phases: phases, context: context, callback: callback };
  213. }
  214. } );
  215. // Remove: `node.events.*eventName* = node.events.remove( listenerID|handler )`
  216. Object.defineProperty( node.events, "remove", {
  217. value: function( listenerID ) {
  218. // For 0.6.23 and earlier, listeners were removed using a direct reference to
  219. // the handler. For 0.6.24 and later a `listenerID` is used. Accept a function
  220. // for compatability with components written for 0.6.23 or earlier. The event
  221. // setter will translate the function to an id.
  222. if ( typeof listenerID === "function" || listenerID instanceof Function ) {
  223. return { remove: true, handler: listenerID };
  224. } else {
  225. return { remove: true, id: listenerID };
  226. }
  227. }
  228. } );
  229. // Flush: `node.events.*eventName* = node.events.flush( context )`
  230. Object.defineProperty( node.events, "flush", {
  231. value: function( context ) {
  232. return { flush: true, context: context };
  233. }
  234. } );
  235. node.private.listeners = {}; // not delegated to the prototype as with getters, setters, and bodies; findListeners() filters recursion
  236. // Children.
  237. node.children = []; // TODO: connect children's prototype like properties, methods and events do? how, since it's an array? drop the ordered list support and just use an object?
  238. Object.defineProperty( node.children, "node", {
  239. value: node // for node.children accessors (non-enumerable) // TODO: hide this better
  240. } );
  241. Object.defineProperty( node.children, "create", {
  242. value: function( name, component, callback /* ( child ) */ ) { // "this" is node.children
  243. // Interpret `node.children.create( name, callback )` as
  244. // `node.children.create( name, undefined, callback )`.
  245. if ( typeof component === "function" || component instanceof Function ) {
  246. callback = component;
  247. component = undefined;
  248. }
  249. // Accept `node.children.create( name )` and treat it as
  250. // `node.children.create( name, {} )`.
  251. component = component || {};
  252. // Make the call. If a callback is provided, wrap it and translate the ID to a
  253. // node reference.
  254. if ( callback ) {
  255. self.kernel.createChild( this.node.id, name, VWFJavaScript.componentKernelFromJS.call( self, component ), undefined, undefined, function( childID ) {
  256. callback.call( node, self.nodes[childID] );
  257. } );
  258. } else {
  259. return self.kernel.createChild( this.node.id, name, VWFJavaScript.componentKernelFromJS.call( self, component ) );
  260. }
  261. }
  262. } );
  263. Object.defineProperty( node.children, "delete", {
  264. value: function( child ) {
  265. if ( typeof child === "string" ) {
  266. child = this.node.children[ child ];
  267. }
  268. return self.kernel.deleteNode( child.id );
  269. }
  270. } );
  271. // Attach the child meta events to `node.children.{added,removed}`.
  272. VWFJavaScript.createEventAccessor.call( this, node.children, "added", "children" );
  273. VWFJavaScript.createEventAccessor.call( this, node.children, "removed", "children" );
  274. // Define the "random" and "seed" functions.
  275. Object.defineProperty( node, "random", { // "this" is node
  276. value: function() {
  277. return self.kernel.random( this.id );
  278. }
  279. } );
  280. Object.defineProperty( node, "seed", { // "this" is node
  281. value: function( seed ) {
  282. return self.kernel.seed( this.id, seed );
  283. }
  284. } );
  285. Object.defineProperty( node, "randomHash", { // "this" is node
  286. value: function() {
  287. let random = self.kernel.random( this.id )
  288. return Crypto.MD5(JSON.stringify(random)).toString().substring(0, 16)
  289. }
  290. } );
  291. // Define the "time", "client", and "moniker" properties.
  292. Object.defineProperty( node, "time", { // TODO: only define on shared "node" prototype?
  293. get: function() {
  294. return self.kernel.time();
  295. },
  296. enumerable: true,
  297. } );
  298. Object.defineProperty( node, "client", { // TODO: only define on shared "node" prototype?
  299. get: function() {
  300. return self.kernel.client();
  301. },
  302. enumerable: true,
  303. } );
  304. Object.defineProperty( node, "moniker", { // TODO: only define on shared "node" prototype?
  305. get: function() {
  306. return self.kernel.moniker();
  307. },
  308. enumerable: true,
  309. } );
  310. Object.defineProperty( node, "find", {
  311. value: function( matchPattern, callback /* ( match ) */ ) { // "this" is node
  312. if ( callback ) {
  313. self.kernel.find( this.id, matchPattern, true, function( matchID ) {
  314. callback.call( node, self.nodes[matchID] );
  315. } );
  316. } else { // TODO: future iterator proxy
  317. var findResults = self.kernel.find( this.id, matchPattern, true );
  318. if ( findResults )
  319. return findResults.map( function( matchID ) {
  320. return self.nodes[matchID];
  321. } );
  322. }
  323. }
  324. } );
  325. Object.defineProperty( node, "test", {
  326. value: function( matchPattern, testNode ) { // "this" is node
  327. return self.kernel.test( this.id, matchPattern, testNode.id, true );
  328. }
  329. } );
  330. // Define a "future" proxy so that for any this.property, this.method, or this.event, we
  331. // can reference this.future( when, callback ).property/method/event and have the
  332. // expression evaluated at the future time.
  333. Object.defineProperty( node, "in", { // TODO: only define on shared "node" prototype?
  334. value: function( when, callback ) { // "this" is node
  335. return VWFJavaScript.refreshedFuture.call( self, this, -when, callback ); // relative time
  336. },
  337. enumerable: true,
  338. } );
  339. Object.defineProperty( node, "at", { // TODO: only define on shared "node" prototype?
  340. value: function( when, callback ) { // "this" is node
  341. return VWFJavaScript.refreshedFuture.call( self, this, when, callback ); // absolute time
  342. },
  343. enumerable: true,
  344. } );
  345. Object.defineProperty( node, "future", { // same as "in" // TODO: only define on shared "node" prototype?
  346. get: function() {
  347. return this.in;
  348. },
  349. enumerable: true,
  350. } );
  351. node.private.future = Object.create( prototype.private ?
  352. prototype.private.future : Object.prototype
  353. );
  354. Object.defineProperty( node.private.future, "private", {
  355. value: {
  356. when: 0,
  357. callback: undefined,
  358. change: 0,
  359. }
  360. } );
  361. node.private.change = 1; // incremented whenever "future"-related changes occur
  362. },
  363. // -- initializingNode ---------------------------------------------------------------------
  364. // Invoke an initialize() function if one exists.
  365. initializingNode: function( nodeID, childID, childExtendsID, childImplementsIDs,
  366. childSource, childType, childIndex, childName ) {
  367. var node = this.nodes[nodeID];
  368. var child = this.nodes[childID];
  369. this.hookUpAPIs(child);
  370. var scriptText =
  371. "this.hasOwnProperty( 'initialize' ) && " +
  372. "( typeof this.initialize === 'function' || this.initialize instanceof Function ) && " +
  373. "this.initialize()";
  374. // Call the child's initializer.
  375. try {
  376. ( function( scriptText ) { return eval( scriptText ) } ).call( child, scriptText );
  377. } catch ( e ) {
  378. this.logger.warnx( "initializingNode", childID,
  379. "exception in initialize:", VWFJavaScript.utility.exceptionMessage( e ) );
  380. }
  381. // The node is fully initialized at this point
  382. // Link to the parent.
  383. //
  384. // The parent reference is only defined once the node is fully initialized.
  385. // It is not defined earlier since components should be able to stand alone
  386. // without depending on external nodes.
  387. //
  388. // Additionally, since parts of the application may become ready in a different
  389. // order on other clients, referring to properties in other parts of the
  390. // application may lead to consistency errors.
  391. child.parent = node;
  392. if ( node ) {
  393. node.children[childIndex] = child;
  394. if ( parseInt( childName ).toString() !== childName ) {
  395. node.children[childName] = child;
  396. }
  397. node.hasOwnProperty( childName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  398. ( node[childName] = child );
  399. }
  400. return undefined;
  401. },
  402. // -- initializingNodeFromPrototype --------------------------------------------------------
  403. // Invoke an initialize() function from `childInitializingNodeID` on `childID` if one exists.
  404. initializingNodeFromPrototype: function( nodeID, childID, childInitializingNodeID ) {
  405. var child = this.nodes[childID];
  406. var initializer = this.nodes[childInitializingNodeID];
  407. // Call the prototype's initializer on the child.
  408. try {
  409. var prototypeHasInitialize = ( initializer.hasOwnProperty( 'initialize' ) &&
  410. ( typeof initializer.initialize === 'function' ||
  411. initializer.initialize instanceof Function ) );
  412. if ( prototypeHasInitialize ) {
  413. return initializer.initialize.call( child );
  414. }
  415. } catch ( e ) {
  416. this.logger.warnx( "initializingNodeFromPrototype", childID,
  417. "exception in initialize:", VWFJavaScript.utility.exceptionMessage( e ) );
  418. }
  419. return undefined;
  420. },
  421. // -- deletingNode -------------------------------------------------------------------------
  422. deletingNode: function( nodeID ) {
  423. var child = this.nodes[nodeID];
  424. if(!child)
  425. return
  426. var node = child.parent;
  427. if ( node ) {
  428. var index = node.children.indexOf( child );
  429. if ( index >= 0 ) {
  430. node.children.splice( index, 1 );
  431. }
  432. delete node.children[child.name]; // TODO: conflict if childName is parseable as a number
  433. if ( node[child.name] === child ) {
  434. delete node[child.name]; // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  435. }
  436. child.parent = undefined;
  437. }
  438. delete this.nodes[nodeID];
  439. },
  440. // -- addingChild --------------------------------------------------------------------------
  441. addingChild: function( nodeID, childID, childName ) {
  442. },
  443. // -- removingChild ------------------------------------------------------------------------
  444. removingChild: function( nodeID, childID ) {
  445. var node = this.nodes[nodeID];
  446. var child = this.nodes[childID];
  447. child.parent = undefined;
  448. if ( node ) {
  449. node.children.splice( node.children.indexOf( child ), 1 );
  450. delete node.children[child.name]; // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  451. delete node[child.name]; // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  452. }
  453. },
  454. // -- creatingProperty ---------------------------------------------------------------------
  455. creatingProperty: function( nodeID, propertyName, propertyValue, propertyGet, propertySet ) {
  456. var node = this.nodes[nodeID];
  457. var self = this;
  458. var getter = propertyGet && // TODO: assuming javascript here; how to specify script type?
  459. VWFJavaScript.functionFromHandler( { body: propertyGet, type: VWFJavaScript.scriptMediaType },
  460. logGetterException );
  461. if ( getter ) {
  462. node.private.getters[ propertyName ] = getter;
  463. } else {
  464. node.private.getters[ propertyName ] = true; // set a guard value so that we don't call prototype getters on value properties
  465. }
  466. var setter = propertySet && // TODO: assuming javascript here; how to specify script type?
  467. VWFJavaScript.functionFromHandler( { parameters: [ "value" ], body: propertySet, type: VWFJavaScript.scriptMediaType },
  468. logSetterException );
  469. if ( setter ) {
  470. node.private.setters[ propertyName ] = setter;
  471. } else {
  472. node.private.setters[ propertyName ] = true; // set a guard value so that we don't call prototype setters on value properties
  473. }
  474. function logGetterException( exception ) {
  475. self.logger.warnx( "creatingProperty", nodeID, propertyName, propertyValue,
  476. "exception evaluating getter:", VWFJavaScript.utility.exceptionMessage( exception ) );
  477. }
  478. function logSetterException( exception ) {
  479. self.logger.warnx( "creatingProperty", nodeID, propertyName, propertyValue,
  480. "exception evaluating setter:", VWFJavaScript.utility.exceptionMessage( exception ) );
  481. }
  482. return this.initializingProperty( nodeID, propertyName, propertyValue );
  483. },
  484. // -- initializingProperty -----------------------------------------------------------------
  485. initializingProperty: function( nodeID, propertyName, propertyValue ) {
  486. var node = this.nodes[nodeID];
  487. VWFJavaScript.createPropertyAccessor.call( this, node.properties, propertyName );
  488. node.hasOwnProperty( propertyName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  489. VWFJavaScript.createPropertyAccessor.call( this, node, propertyName );
  490. // Invalidate the "future" cache.
  491. node.private.change++;
  492. return propertyValue !== undefined ?
  493. this.settingProperty( nodeID, propertyName, propertyValue ) : undefined;
  494. },
  495. // TODO: deletingProperty
  496. // -- settingProperty ----------------------------------------------------------------------
  497. settingProperty: function( nodeID, propertyName, propertyValue ) {
  498. var node = this.nodes[nodeID];
  499. if ( ! node ) return; // TODO: patch until full-graph sync is working; drivers should be able to assume that nodeIDs refer to valid objects
  500. var setter = node.private.setters && node.private.setters[propertyName];
  501. if ( setter && setter !== true ) { // is there is a setter (and not just a guard value)
  502. try {
  503. var valueJS = VWFJavaScript.valueJSFromKernel.call( this, propertyValue );
  504. var resultJS = setter.call( node, valueJS );
  505. return VWFJavaScript.valueKernelFromJS.call( this, resultJS );
  506. } catch ( e ) {
  507. this.logger.warnx( "settingProperty", nodeID, propertyName, propertyValue,
  508. "exception in setter:", VWFJavaScript.utility.exceptionMessage( e ) );
  509. }
  510. }
  511. return undefined;
  512. },
  513. // -- gettingProperty ----------------------------------------------------------------------
  514. gettingProperty: function( nodeID, propertyName, propertyValue ) {
  515. var node = this.nodes[nodeID];
  516. if ( ! node ) return;
  517. var getter = node.private.getters && node.private.getters[propertyName];
  518. if ( getter && getter !== true ) { // is there is a getter (and not just a guard value)
  519. try {
  520. var resultJS = getter.call( node );
  521. return VWFJavaScript.valueKernelFromJS.call( this, resultJS );
  522. } catch ( e ) {
  523. this.logger.warnx( "gettingProperty", nodeID, propertyName, propertyValue,
  524. "exception in getter:", VWFJavaScript.utility.exceptionMessage( e ) );
  525. }
  526. }
  527. return undefined;
  528. },
  529. // -- creatingMethod -----------------------------------------------------------------------
  530. creatingMethod: function( nodeID, methodName, methodParameters, methodBody ) {
  531. var node = this.nodes[nodeID];
  532. VWFJavaScript.createMethodAccessor.call( this, node.methods, methodName );
  533. node.hasOwnProperty( methodName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  534. VWFJavaScript.createMethodAccessor.call( this, node, methodName );
  535. // Invalidate the "future" cache.
  536. node.private.change++;
  537. // Delegate to `settingMethod`.
  538. return this.settingMethod( nodeID, methodName, {
  539. parameters: methodParameters,
  540. body: methodBody,
  541. type: typeof methodBody === "string" || methodBody instanceof String ?
  542. VWFJavaScript.scriptMediaType : undefined, // TODO: heuristic duplicated in vwf.js `normalizedHandler`.
  543. } );
  544. },
  545. // TODO: deletingMethod
  546. // -- settingMethod ------------------------------------------------------------------------
  547. settingMethod: function( nodeID, methodName, methodHandler ) {
  548. var node = this.nodes[nodeID];
  549. var self = this;
  550. var body = VWFJavaScript.functionFromHandler( methodHandler, logException,
  551. vwf.configuration[ "preserve-script-closures" ] );
  552. if ( body ) {
  553. node.private.bodies[ methodName ] = body;
  554. return VWFJavaScript.handlerFromFunction( body ); // TODO: shortcut to avoid retrieving this?
  555. } else {
  556. delete node.private.bodies[ methodName ];
  557. }
  558. function logException( exception ) {
  559. self.logger.warnx( "settingMethod", nodeID, methodName, methodHandler.parameters,
  560. "exception evaluating body:", VWFJavaScript.utility.exceptionMessage( exception ) );
  561. }
  562. return undefined;
  563. },
  564. // -- gettingMethod ------------------------------------------------------------------------
  565. gettingMethod: function( nodeID, methodName ) {
  566. var node = this.nodes[nodeID];
  567. var body = node.private.bodies && node.private.bodies[methodName];
  568. if ( body ) {
  569. return VWFJavaScript.handlerFromFunction( body );
  570. }
  571. return undefined;
  572. },
  573. // -- callingMethod ------------------------------------------------------------------------
  574. callingMethod: function( nodeID, methodName, methodParameters ) {
  575. var node = this.nodes[nodeID];
  576. var body = node.private.bodies && node.private.bodies[methodName];
  577. if ( body ) {
  578. try {
  579. var parametersJS = VWFJavaScript.parametersJSFromKernel.call( this, methodParameters );
  580. var resultJS = body.apply( node, parametersJS );
  581. return VWFJavaScript.valueKernelFromJS.call( this, resultJS );
  582. } catch ( e ) {
  583. this.logger.warnx( "callingMethod", nodeID, methodName, methodParameters, // TODO: limit methodParameters for log
  584. "exception:", VWFJavaScript.utility.exceptionMessage( e ) );
  585. }
  586. }
  587. return undefined;
  588. },
  589. // -- creatingEvent ------------------------------------------------------------------------
  590. creatingEvent: function( nodeID, eventName, eventParameters ) {
  591. var node = this.nodes[nodeID];
  592. VWFJavaScript.createEventAccessor.call( this, node.events, eventName );
  593. node.hasOwnProperty( eventName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  594. VWFJavaScript.createEventAccessor.call( this, node, eventName );
  595. // Invalidate the "future" cache.
  596. node.private.change++;
  597. },
  598. // -- addingEventListener ------------------------------------------------------------------
  599. addingEventListener: function( nodeID, eventName, eventListenerID, eventHandler, eventContextID, eventPhases ) {
  600. var node = this.nodes[nodeID];
  601. // Create the listeners collection if this is the first listener added for an event on a
  602. // prototype.
  603. if ( ! node.private.listeners[eventName] ) {
  604. node.private.listeners[eventName] = [];
  605. }
  606. // Build a `Listener` from the `Handler` and the context and phases.
  607. var eventListener = VWFJavaScript.utility.merge( eventHandler, {
  608. context: eventContextID,
  609. phases: eventPhases,
  610. } );
  611. // Delegate to `settingEventListener`.
  612. return this.settingEventListener( nodeID, eventName, eventListenerID, eventListener ) ?
  613. true : undefined;
  614. },
  615. // -- removingEventListener ----------------------------------------------------------------
  616. removingEventListener: function( nodeID, eventName, eventListenerID ) {
  617. var node = this.nodes[nodeID];
  618. var listeners = node.private.listeners[eventName];
  619. if ( listeners && listeners[ eventListenerID ] ) {
  620. delete listeners[ eventListenerID ];
  621. return true;
  622. }
  623. return undefined;
  624. },
  625. // -- settingEventListener -----------------------------------------------------------------
  626. settingEventListener: function( nodeID, eventName, eventListenerID, eventListener ) {
  627. var node = this.nodes[nodeID];
  628. var self = this;
  629. var listeners = node.private.listeners[eventName];
  630. var handler = VWFJavaScript.functionFromHandler( eventListener, logException,
  631. vwf.configuration[ "preserve-script-closures" ] );
  632. if ( handler ) {
  633. listeners[ eventListenerID ] = {
  634. handler: handler,
  635. context: eventListener.context,
  636. phases: eventListener.phases,
  637. };
  638. // Kernel actions that set a value allow the driver to modify the value assigned.
  639. // The result of the action is the actually-assigned value reported by the driver.
  640. // Here, we should return a `Listener` derived from the function we just rendered so
  641. // that `kernel.setEvent` will return the same result that a following
  642. // `kernel.getEvent` would. However, since `Function.toString` is relatively heavy,
  643. // we'll just return the incoming value until there is a demonstrated need for the
  644. // precise result.
  645. // return utility.merge( handlerFromFunction( listener.handler ), {
  646. // context: listener.context,
  647. // phases: listener.phases,
  648. // } );
  649. return eventListener;
  650. } else {
  651. delete listeners[ eventListenerID ];
  652. }
  653. function logException( exception ) {
  654. self.logger.warnx( "settingEventListener", nodeID, eventName, eventListenerID,
  655. "exception evaluating listener:", VWFJavaScript.utility.exceptionMessage( exception ) );
  656. }
  657. return undefined;
  658. },
  659. // -- gettingEventListener -----------------------------------------------------------------
  660. gettingEventListener: function( nodeID, eventName, eventListenerID ) {
  661. var node = this.nodes[nodeID];
  662. var listeners = node.private.listeners[eventName];
  663. if ( listeners ) {
  664. var listener = listeners[ eventListenerID ];
  665. return VWFJavaScript.utility.merge( VWFJavaScript.handlerFromFunction( listener.handler ), {
  666. context: listener.context,
  667. phases: listener.phases,
  668. } );
  669. }
  670. return undefined;
  671. },
  672. // -- flushingEventListeners ---------------------------------------------------------------
  673. flushingEventListeners: function( nodeID, eventName, eventContextID ) {
  674. // Prepare the return value
  675. var removedListenerIDs = [];
  676. // Extract the listeners of the specified node
  677. var node = this.nodes[ nodeID ];
  678. var listeners = node.private.listeners[ eventName ];
  679. // If listeners exist for the given eventName, loop through them, removing any for which
  680. // the context is the node specified by the parameter eventContextID
  681. if ( listeners ) {
  682. listeners.forEach( function( listener, listenerID ) {
  683. if ( listener.context === eventContextID ) {
  684. delete listeners[ listenerID ];
  685. removedListenerIDs.push( listenerID );
  686. }
  687. } );
  688. }
  689. return removedListenerIDs;
  690. },
  691. // -- firingEvent --------------------------------------------------------------------------
  692. firingEvent: function( nodeID, eventName, eventParameters ) {
  693. var phase = eventParameters && eventParameters.phase; // the phase is smuggled 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
  694. var node = this.nodes[nodeID];
  695. var listeners = VWFJavaScript.findListeners( node, eventName );
  696. var parametersJS = VWFJavaScript.parametersJSFromKernel.call( this, eventParameters );
  697. var self = this;
  698. // Call the handlers registered for the event, and calculate the logical OR of each
  699. // result. Normally, callers to fireEvent() ignore the handler result, but dispatched
  700. // events use the return value to determine when an event has been handled as it bubbles
  701. // up from its target.
  702. var handled = listeners && listeners.reduce( function( handled, listener ) {
  703. // Call the handler. If a phase is provided, only call handlers tagged for that
  704. // phase.
  705. try {
  706. if ( ! phase || listener.phases && listener.phases.indexOf( phase ) >= 0 ) {
  707. var contextNode = self.nodes[ listener.context ] || self.nodes[ 0 ]; // default context is the global root // TODO: this presumes this.creatingNode( undefined, 0 ) is retained above
  708. var resultJS = listener.handler.apply( contextNode, parametersJS );
  709. var result = VWFJavaScript.valueKernelFromJS.call( self, resultJS );
  710. return handled || result || result === undefined; // interpret no return as "return true"
  711. }
  712. } catch ( e ) {
  713. self.logger.warnx( "firingEvent", nodeID, eventName, eventParameters, // TODO: limit eventParameters for log
  714. "exception:", VWFJavaScript.utility.exceptionMessage( e ) );
  715. }
  716. return handled;
  717. }, false );
  718. return handled;
  719. },
  720. // -- executing ----------------------------------------------------------------------------
  721. executing: function( nodeID, scriptText, scriptType ) {
  722. var node = this.nodes[nodeID];
  723. if ( scriptType == VWFJavaScript.scriptMediaType ) {
  724. try {
  725. var resultJS = ( function( scriptText ) { return eval( scriptText ) } ).call( node, scriptText || "" );
  726. return VWFJavaScript.valueKernelFromJS.call( this, resultJS );
  727. } catch ( e ) {
  728. this.logger.warnx( "executing", nodeID,
  729. ( scriptText || "" ).replace( /\s+/g, " " ).substring( 0, 100 ), scriptType, "exception:", VWFJavaScript.utility.exceptionMessage( e ) );
  730. }
  731. }
  732. return undefined;
  733. },
  734. hookUpAPIs: function(node)
  735. {
  736. let self = this;
  737. let id = node.id;
  738. if(id == vwf.application())
  739. {
  740. node.findNode = function(displayName,node)
  741. {
  742. if(displayName) displayName = displayName;
  743. if(!node)
  744. node = this;
  745. if(node && node.properties && node.properties.displayName == displayName)
  746. return node;
  747. var ret = null;
  748. for(var i =0; i < node.children.length; i++)
  749. {
  750. ret = this.findNode(displayName,node.children[i]);
  751. if(ret) return ret;
  752. }
  753. return ret;
  754. }
  755. node.findNodeByID = function(id)
  756. {
  757. if(!id) return null;
  758. return self.nodes[id];
  759. }
  760. }
  761. }
  762. } );
  763. }
  764. // == Private functions ========================================================================
  765. // -- proxiedBehavior --------------------------------------------------------------------------
  766. static proxiedBehavior( prototype, behavior ) { // invoke with the model as "this" // TODO: this is a lot like createProperty()/createMethod()/createEvent(), and refreshedFuture(). Find a way to merge. // TODO: nodes need to keep a list of proxies on them and callback here to refresh after changes
  767. var self = this;
  768. var proxy = Object.create( prototype );
  769. Object.defineProperty( proxy, "private", {
  770. value: {}
  771. } );
  772. proxy.private.origin = behavior; // the node we're the proxy for
  773. Object.defineProperty( proxy, "id", {
  774. value: behavior.id,
  775. enumerable: true,
  776. } );
  777. proxy.name = behavior.name;
  778. proxy.parent = behavior.parent;
  779. proxy.source = behavior.source;
  780. proxy.type = behavior.type;
  781. proxy.initialize = behavior.initialize;
  782. proxy.properties = Object.create( prototype.properties || Object.prototype, {
  783. node: { value: proxy } // for proxy.properties accessors (non-enumerable) // TODO: hide this better
  784. } );
  785. proxy.private.getters = Object.create( prototype.private ?
  786. prototype.private.getters : Object.prototype
  787. );
  788. proxy.private.setters = Object.create( prototype.private ?
  789. prototype.private.setters : Object.prototype
  790. );
  791. for ( var propertyName in behavior.properties ) {
  792. if ( behavior.properties.hasOwnProperty( propertyName ) ) {
  793. ( function( propertyName ) {
  794. VWFJavaScript.createPropertyAccessor.call( self, proxy.properties, propertyName );
  795. proxy.hasOwnProperty( propertyName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  796. VWFJavaScript.createPropertyAccessor.call( self, proxy, propertyName );
  797. } )( propertyName );
  798. if ( behavior.private.getters.hasOwnProperty( propertyName ) ) {
  799. proxy.private.getters[propertyName] = behavior.private.getters[propertyName];
  800. }
  801. if ( behavior.private.setters.hasOwnProperty( propertyName ) ) {
  802. proxy.private.setters[propertyName] = behavior.private.setters[propertyName];
  803. }
  804. }
  805. }
  806. proxy.methods = Object.create( prototype.methods || Object.prototype, {
  807. node: { value: proxy } // for proxy.methods accessors (non-enumerable) // TODO: hide this better
  808. } );
  809. proxy.private.bodies = Object.create( prototype.private ?
  810. prototype.private.bodies : Object.prototype
  811. );
  812. for ( var methodName in behavior.methods ) {
  813. if ( behavior.methods.hasOwnProperty( methodName ) ) {
  814. ( function( methodName ) {
  815. VWFJavaScript.createMethodAccessor.call( self, proxy.methods, methodName );
  816. proxy.hasOwnProperty( methodName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  817. VWFJavaScript.createMethodAccessor.call( self, proxy, methodName );
  818. } )( methodName );
  819. if ( behavior.private.bodies.hasOwnProperty( methodName ) ) {
  820. proxy.private.bodies[methodName] = behavior.private.bodies[methodName];
  821. }
  822. }
  823. }
  824. proxy.events = Object.create( prototype.events || Object.prototype, {
  825. node: { value: proxy } // for proxy.events accessors (non-enumerable) // TODO: hide this better
  826. } );
  827. proxy.private.listeners = {}; // not delegated to the prototype as with getters, setters, and bodies; findListeners() filters recursion
  828. for ( var eventName in behavior.events ) {
  829. if ( behavior.events.hasOwnProperty( eventName ) ) {
  830. ( function( eventName ) {
  831. VWFJavaScript.createEventAccessor.call( self, proxy.events, eventName );
  832. proxy.hasOwnProperty( eventName ) || // TODO: recalculate as properties, methods, events and children are created and deleted; properties take precedence over methods over events over children, for example
  833. VWFJavaScript.createEventAccessor.call( self, proxy, eventName );
  834. } )( eventName );
  835. }
  836. }
  837. for ( var eventName in behavior.private.listeners ) { // outside of the behavior.events loop as with getters, setters, and bodies; listeners may appear above the event definition
  838. if ( behavior.private.listeners.hasOwnProperty( eventName ) ) {
  839. proxy.private.listeners[eventName] = behavior.private.listeners[eventName];
  840. }
  841. }
  842. proxy.private.future = Object.create( prototype.private ?
  843. prototype.private.future : Object.prototype
  844. );
  845. Object.defineProperty( proxy.private.future, "private", {
  846. value: {
  847. when: 0,
  848. callback: undefined,
  849. change: 0,
  850. }
  851. } );
  852. proxy.private.change = behavior.private.change;
  853. return proxy;
  854. }
  855. // -- refreshedFuture --------------------------------------------------------------------------
  856. static refreshedFuture( node, when, callback ) { // invoke with the model as "this"
  857. var self = this;
  858. if ( Object.getPrototypeOf( node ).private ) {
  859. VWFJavaScript.refreshedFuture.call( this, Object.getPrototypeOf( node ) );
  860. }
  861. var future = node.private.future;
  862. future.private.when = when;
  863. future.private.callback = callback; // TODO: would like to be able to remove this reference after the future call has completed
  864. if ( future.private.change < node.private.change ) { // only if out of date
  865. Object.defineProperty( future, "id", {
  866. value: node.id,
  867. enumerable: true,
  868. } );
  869. future.properties = Object.create( Object.getPrototypeOf( future ).properties || Object.prototype, {
  870. node: { value: future } // for future.properties accessors (non-enumerable) // TODO: hide this better
  871. } );
  872. for ( var propertyName in node.properties ) {
  873. if ( node.properties.hasOwnProperty( propertyName ) ) {
  874. ( function( propertyName ) {
  875. VWFJavaScript.createPropertyAccessor.call( self, future.properties, propertyName );
  876. future.hasOwnProperty( propertyName ) || // TODO: calculate so that properties take precedence over methods over events, for example
  877. VWFJavaScript.createPropertyAccessor.call( self, future, propertyName );
  878. } )( propertyName );
  879. }
  880. }
  881. future.methods = Object.create( Object.getPrototypeOf( future ).methods || Object.prototype, {
  882. node: { value: future } // for future.methods accessors (non-enumerable) // TODO: hide this better
  883. } );
  884. for ( var methodName in node.methods ) {
  885. if ( node.methods.hasOwnProperty( methodName ) ) {
  886. ( function( methodName ) {
  887. VWFJavaScript.createMethodAccessor.call( self, future.methods, methodName, true );
  888. future.hasOwnProperty( methodName ) || // TODO: calculate so that properties take precedence over methods over events, for example
  889. VWFJavaScript.createMethodAccessor.call( self, future, methodName, true );
  890. } )( methodName );
  891. }
  892. }
  893. future.events = Object.create( Object.getPrototypeOf( future ).events || Object.prototype, {
  894. node: { value: future } // for future.events accessors (non-enumerable) // TODO: hide this better
  895. } );
  896. for ( var eventName in node.events ) {
  897. if ( node.events.hasOwnProperty( eventName ) ) {
  898. ( function( eventName ) {
  899. VWFJavaScript.createEventAccessor.call( self, future.events, eventName, undefined, true );
  900. future.hasOwnProperty( eventName ) || // TODO: calculate so that properties take precedence over methods over events, for example
  901. VWFJavaScript.createEventAccessor.call( self, future, eventName, undefined, true );
  902. } )( eventName );
  903. }
  904. }
  905. future.private.change = node.private.change;
  906. }
  907. return future;
  908. }
  909. /// Define a (JavaScript) accessor property on a node or a node's `properties` collection that
  910. /// will manipulate a (VWF) property on the node.
  911. ///
  912. /// Reading `node.properties.name` invokes the `get` accessor, which calls `kernel.getProperty`
  913. /// to return the value for the property on the node. Writing `node.properties.name` invokes
  914. /// the `set` accessor, which calls `kernel.setProperty` to assign a new value to the property
  915. /// on its node.
  916. ///
  917. /// This function must run as a method of the driver. Invoke it as:
  918. /// `createPropertyAccessor.call( driver, container, propertyName )`.
  919. ///
  920. /// @param {Object} container
  921. /// A `node` or `node.properties` object to receive the property.
  922. /// @param {String} propertyName
  923. /// The name of the property to create on `container`.
  924. static createPropertyAccessor( container, propertyName ) {
  925. var self = this;
  926. Object.defineProperty( container, propertyName, {
  927. // On read, call `kernel.getProperty` and return the result.
  928. get: function() { // `this` is the container
  929. var node = this.node || this; // the node via node.properties.node, or just node
  930. var resultKernel = self.kernel.getProperty( node.id, propertyName,
  931. node.private.when, node.private.callback );
  932. return VWFJavaScript.valueJSFromKernel.call( self, resultKernel );
  933. },
  934. // On write, pass the assigned value to `kernel.setProperty`.
  935. set: function( value ) { // `this` is the container
  936. var node = this.node || this; // the node via node.properties.node, or just node
  937. var valueKernel = VWFJavaScript.valueKernelFromJS.call( self, value );
  938. self.kernel.setProperty( node.id, propertyName, valueKernel,
  939. node.private.when, node.private.callback );
  940. },
  941. enumerable: true,
  942. } );
  943. }
  944. /// Define an accessor property on a node or a node's `methods` collection that manipulates a
  945. /// method on the node.
  946. ///
  947. /// Reading `node.methods.name` returns a function that when called calls `kernel.callMethod` to
  948. /// invoke the method on the node. Writing a function object to `node.methods.name` will set the
  949. /// method body to the assigned function.
  950. ///
  951. /// This function must run as a method of the driver. Invoke it as:
  952. /// `createMethodAccessor.call( driver, container, methodName )`.
  953. ///
  954. /// @param {Object} container
  955. /// A `node` or `node.methods` object to receive the property.
  956. /// @param {String} methodName
  957. /// The name of the property to create on `container`.
  958. /// @param {Boolean} [unsettable]
  959. /// When truthy, don't create the `set` accessor. An unsettable method property doesn't allow
  960. /// the method body to be changed.
  961. static createMethodAccessor( container, methodName, unsettable ) {
  962. var self = this;
  963. Object.defineProperty( container, methodName, {
  964. // On read, return a function that calls `kernel.callMethod` when invoked.
  965. get: function() { // `this` is the container
  966. return function( /* parameter1, parameter2, ... */ ) { // `this` is the container
  967. let node = this.node || this; // the node via node.methods.node, or just node
  968. var argumentsKernel = VWFJavaScript.parametersKernelFromJS.call( self, arguments );
  969. var resultKernel = self.kernel.callMethod( node.id, methodName, argumentsKernel,
  970. node.private.when, node.private.callback );
  971. return VWFJavaScript.valueJSFromKernel.call( self, resultKernel );
  972. };
  973. },
  974. // On write, update the method body. `unsettable` methods don't accept writes.
  975. set: unsettable ? undefined : function( value ) { // `this` is the container
  976. let node = this.node || this; // the node via node.methods.node, or just node
  977. self.kernel.setMethod( node.id, methodName,
  978. VWFJavaScript.handlerFromFunction( value, vwf.configuration[ "preserve-script-closures" ] ) );
  979. },
  980. enumerable: true,
  981. } );
  982. }
  983. /// Define an accessor property on a node or a node's `events` collection that manipulates an
  984. /// event on the node. `createEventAccessor` is also used to define accessor properties at other
  985. /// locations on the node to expose the node's meta events.
  986. ///
  987. /// Reading `node.events.name` returns a function that when called calls `kernel.fireEvent` to
  988. /// fire the event from the node. Writing a function object to `node.events.name` will add the
  989. /// assigned function as a new listener using default parameters. To add a listener with
  990. /// specified paramters, call the `node.events.add` helper function and assign the result to
  991. /// `node.events.name`. Remove a listener by calling the `node.events.remove` helper and
  992. /// assigning the result. Flush a set of listeners with the `node.events.flush` helper.
  993. ///
  994. /// This function must run as a method of the driver. Invoke it as:
  995. /// `createEventAccessor.call( driver, container, eventName [, eventNamespace ] [, unsettable ] )`.
  996. ///
  997. /// @param {Object} container
  998. /// A `node` or `node.events` object to receive the property. Meta events will attach to
  999. /// `node.properties`, `node.methods`, `node.events`, and `node.children` as well.
  1000. /// @param {String} eventName
  1001. /// The name of the property to create on `container`.
  1002. /// @param {String} [eventNamespace]
  1003. /// For meta events, the namespace associated with the event.
  1004. /// @param {Boolean} [unsettable]
  1005. /// When truthy, don't create the `set` accessor. An unsettable event property can't add or
  1006. /// remove listeners.
  1007. static createEventAccessor( container, eventName, eventNamespace, unsettable ) {
  1008. var self = this;
  1009. Object.defineProperty( container, eventName, {
  1010. // On read, return a function that calls `kernel.fireEvent` when invoked. Namespaced
  1011. // events (which are meta events and controlled by the kernel) are ungettable and can't
  1012. // be fired by the application.
  1013. get: eventNamespace ? undefined : function() { // `this` is the container
  1014. var node = this.node || this; // the node via node.*collection*.node, or just node
  1015. return function( /* parameter1, parameter2, ... */ ) { // `this` is the container
  1016. var argumentsKernel = VWFJavaScript.parametersKernelFromJS.call( self, arguments );
  1017. var resultKernel = self.kernel.fireEvent( node.id, eventName, argumentsKernel,
  1018. node.private.when, node.private.callback );
  1019. return VWFJavaScript.valueJSFromKernel.call( self, resultKernel );
  1020. };
  1021. },
  1022. // On write, update the listeners. `unsettable` events don't accept writes.
  1023. set: unsettable ? undefined : function( value ) { // `this` is the container
  1024. var node = this.node || this; // the node via node.*collection*.node, or just node
  1025. var namespacedName = eventNamespace ? [ eventNamespace, eventName ] : eventName;
  1026. if ( typeof value === "function" || value instanceof Function ) {
  1027. // `container.*eventName* = handler` (context is the target node).
  1028. addListener( value, node );
  1029. } else if ( value.add ) {
  1030. // `container.*eventName* = node.events.add( handler, phases, context, callback /* listenerID */ )`.
  1031. if ( ! value.phases || value.phases instanceof Array ) {
  1032. addListener( value.handler, value.context, value.phases, value.callback );
  1033. } else {
  1034. addListener( value.handler, value.context, [ value.phases ], value.callback );
  1035. }
  1036. } else if ( value.remove ) {
  1037. // `container.*eventName* = node.events.remove( listenerID|handler )`.
  1038. // For `node.events.remove( listenerID )`, remove using the direct parameter.
  1039. // For `node.events.remove( handler )`, use the id that `addListener` attached
  1040. // to the handler.
  1041. self.kernel.removeEventListener( node.id, namespacedName,
  1042. value.handler ? value.handler.listenerID : value.id );
  1043. } else if ( value.flush ) {
  1044. // `container.*eventName* = node.events.flush( context )`.
  1045. self.kernel.flushEventListeners( node.id, namespacedName,
  1046. value.context && value.context.id );
  1047. }
  1048. function addListener( handler, context, phases, callback ) {
  1049. var listenerID = self.kernel.addEventListener( node.id, namespacedName,
  1050. VWFJavaScript.handlerFromFunction( handler, vwf.configuration[ "preserve-script-closures" ] ),
  1051. context && context.id, phases );
  1052. // For 0.6.23 and earlier, listeners were removed using a direct reference to
  1053. // the handler. For backward compatability, tag the handler with the listener id
  1054. // so that we can retrieve the id if the listener is removed by handler.
  1055. handler.listenerID = listenerID;
  1056. callback && callback.call( node, listenerID );
  1057. }
  1058. },
  1059. // Meta events--including the `properties`, `methods`, and `events` `created` and
  1060. // `deleted` events, and the `children` `added` and `removed` events--are not
  1061. // enumerable.
  1062. enumerable: ! eventNamespace,
  1063. } );
  1064. }
  1065. /// Convert a `Handler` to a JavaScript function.
  1066. ///
  1067. /// @param {Handler} handler
  1068. /// A `Handler` to convert to a function.
  1069. /// @param {function} [errback]
  1070. /// If `errback` is provided, any exception that occurs during the conversion will be passed
  1071. /// to `errback` as `errback( exception )`.
  1072. /// @param {boolean} [bypass]
  1073. /// Expect that `handler.body` is a function object instead of the string representation of
  1074. /// the function body. Return the function without any conversion. This parameter should only
  1075. /// be used in support of the backwards-compatability `preserve-script-closures` configuration
  1076. /// option.
  1077. ///
  1078. /// @returns {function|undefined}
  1079. /// The function generated from `handler`, or `undefined` if `handler` does not describe a
  1080. /// JavaScript function or if the function could not be converted.
  1081. static functionFromHandler( handler, errback /* exception */, bypass ) {
  1082. if ( bypass && ( typeof handler.body === "function" || handler.body instanceof Function ) ) {
  1083. return handler.body;
  1084. } else if ( handler.type === VWFJavaScript.scriptMediaType ) {
  1085. var name = handler.name, parameters = handler.parameters, body = handler.body;
  1086. var parameterString = parameters && parameters.length ?
  1087. " " + parameters.join( ", " ) + " " :
  1088. "";
  1089. var prefix = "function(" + parameterString + ") {";
  1090. var suffix = "}";
  1091. var functionString, indentedBody;
  1092. if ( body && body.length ) {
  1093. if ( body.charAt( body.length-1 ) === "\n" ) {
  1094. indentedBody = body.match( /^[^\S\n]/ ) ? body : body.replace( /^./gm, " $&" );
  1095. functionString = prefix + "\n" + indentedBody + suffix + "\n";
  1096. } else {
  1097. functionString = prefix + " " + body + " " + suffix;
  1098. }
  1099. } else {
  1100. functionString = prefix + suffix;
  1101. }
  1102. try {
  1103. return eval( "( " + functionString + ")" );
  1104. } catch( exception ) {
  1105. errback && errback( exception );
  1106. }
  1107. }
  1108. return undefined;
  1109. }
  1110. /// Convert a JavaScript `function` to a `Handler`.
  1111. ///
  1112. /// @param {function} funcshun
  1113. /// A function to convert to a `Handler`.
  1114. /// @param {boolean} [bypass]
  1115. /// Create an object having the form of a `Handler`, but with the `body` field set to the
  1116. /// function object instead of the string representation of the function body. The `name`,
  1117. /// `parameters`, and `type` fields will not be set. This parameter should only be used in
  1118. /// support of the backwards-compatability `preserve-script-closures` configuration option.
  1119. ///
  1120. /// @returns {Handler|undefined}
  1121. /// The `Handler` generated from `funcshun`, or `undefined` if the function's `toString` could
  1122. /// not be parsed.
  1123. static handlerFromFunction( funcshun, bypass ) {
  1124. var name, parameters, body, type = VWFJavaScript.scriptMediaType;
  1125. var match, leadingMatch, trailingMatch, indention = "";
  1126. if ( bypass ) {
  1127. return {
  1128. body: funcshun,
  1129. };
  1130. } else if ( match = /* assignment! */ VWFJavaScript.functionRegex.exec( funcshun.toString() ) ) {
  1131. name = match[1];
  1132. // Trim the parameter string. Also remove the `/**/` that Chrome adds to the parameter
  1133. // list for functions created using `Function( parameter, ..., body )`. See
  1134. // `NewFunctionString` in http://code.google.com/p/v8/source/browse/trunk/src/v8natives.js.
  1135. var parameterString = match[2].replace( /\/\*.*\*\//, "" ).trim();
  1136. parameters = parameterString.length ? parameterString.split( "," ).map( function( parameter ) {
  1137. return parameter.trim();
  1138. } ) : undefined;
  1139. // Trim the body string. Recognize block vs. inline formatting where possible and retain
  1140. // the existing spacing.
  1141. body = match[3];
  1142. leadingMatch = // leading spacing, if the leading brace is on its own line
  1143. body.match( /^([^\S\n]*\n)([^\S\n]*)/ );
  1144. trailingMatch = // trailing spacing, if the trailing brace is on own line
  1145. body.match( /\n([^\S\n]*)$/ );
  1146. // Trim the leading spaces. If the leading brace was on its own line, delete the empty
  1147. // first line and take the body indention to be the next line's spacing. Otherwise, just
  1148. // trim the beginning of the body.
  1149. if ( leadingMatch ) {
  1150. body = body.substr( leadingMatch[1].length );
  1151. indention = leadingMatch[2];
  1152. } else {
  1153. body = body.replace( /^\s*/, "" );
  1154. }
  1155. // Trim the trailing spaces. If the trailing brace was on its own line, delete its
  1156. // indention and take that as the body indention. The trailing brace indention takes
  1157. // priority over indention taken from the leading line. If the trailing brace was not on
  1158. // its own line, just trim the end of the body.
  1159. if ( trailingMatch ) {
  1160. body = body.substr( -trailingMatch[1] );
  1161. indention = trailingMatch[1];
  1162. } else {
  1163. body = body.replace( /\s*$/, "" );
  1164. }
  1165. // If we recognized the body as an block (not inline with the braces), unindent it and
  1166. // ensure that the last line ends with a newline.
  1167. if ( leadingMatch || trailingMatch ) {
  1168. body = body.replace( new RegExp( "^" + indention, "gm" ), "" );
  1169. body = body.replace( /\n?$/, "\n" );
  1170. }
  1171. return {
  1172. name: name,
  1173. parameters: parameters,
  1174. body: body,
  1175. type: type,
  1176. };
  1177. }
  1178. return undefined;
  1179. }
  1180. // -- findListeners ----------------------------------------------------------------------------
  1181. // TODO: this walks the full prototype chain and is probably horribly inefficient.
  1182. static findListeners( node, eventName, targetOnly ) {
  1183. var prototypeListeners = Object.getPrototypeOf( node ).private ? // get any self-targeted listeners from the prototypes
  1184. VWFJavaScript.findListeners( Object.getPrototypeOf( node ), eventName, true ) : [];
  1185. var nodeListeners = node.private.listeners && node.private.listeners[eventName] || [];
  1186. if ( targetOnly ) {
  1187. return prototypeListeners.concat( nodeListeners.filter( function( listener ) {
  1188. return listener.context === node.id || // in the prototypes, select self-targeted listeners only
  1189. ( node.private.origin && listener.context === node.private.origin.id );
  1190. } ) );
  1191. } else {
  1192. return prototypeListeners.map( function( listener ) { // remap the prototype listeners to target the node
  1193. return { handler: listener.handler, context: node.id, phases: listener.phases };
  1194. } ).concat( nodeListeners );
  1195. }
  1196. }
  1197. /// Transform node references in a component descriptor into kernel-style node references. The
  1198. /// resulting object will be suitable for passing to `kernel.createNode`.
  1199. ///
  1200. /// This function must run as a method of the driver. Invoke it as:
  1201. /// `componentKernelFromJS.call( driver, component )`.
  1202. ///
  1203. /// @param {String|Object} component
  1204. /// A component URI or descriptor. A URI will pass through unchanged (as will all descriptor
  1205. /// fields that aren't node references.)
  1206. ///
  1207. /// @returns {String|Object}
  1208. /// `component` with node references replaced with kernel-style node references.
  1209. static componentKernelFromJS( component ) {
  1210. return VWFJavaScript.valueKernelFromJS.call( this, component );
  1211. }
  1212. /// Convert a parameter array of values using `valueKernelFromJS`.
  1213. ///
  1214. /// This function must run as a method of the driver. Invoke it as:
  1215. /// `parametersKernelFromJS.call( driver, parameters )`.
  1216. ///
  1217. /// @param {Object[]} parameters
  1218. ///
  1219. /// @returns {Object}
  1220. static parametersKernelFromJS( parameters ) {
  1221. return VWFJavaScript.valueKernelFromJS.call( this, parameters );
  1222. }
  1223. /// Convert a parameter array of values using `valueJSFromKernel`.
  1224. ///
  1225. /// This function must run as a method of the driver. Invoke it as:
  1226. /// `parametersJSFromKernel.call( driver, parameters )`.
  1227. ///
  1228. /// @param {Object[]} parameters
  1229. ///
  1230. /// @returns {Object}
  1231. static parametersJSFromKernel( parameters ) {
  1232. return VWFJavaScript.valueJSFromKernel.call( this, parameters );
  1233. }
  1234. /// Convert node references into special values that can pass through the kernel. These values
  1235. /// are wrapped in such a way that they won't be confused with any other application value, and
  1236. /// they will be replicated correctly by the kernel.
  1237. ///
  1238. /// Other values are returned unchanged. Use `valueJSFromKernel` to retrieve the original.
  1239. ///
  1240. /// This function must run as a method of the driver. Invoke it as:
  1241. /// `valueKernelFromJS.call( driver, value )`.
  1242. ///
  1243. /// @param {Object} value
  1244. ///
  1245. /// @returns {Object}
  1246. static valueKernelFromJS( value ) {
  1247. var self = this;
  1248. return VWFJavaScript.utility.transform( value, function( object, names, depth, finished ) {
  1249. if ( VWFJavaScript.valueIsNode.call( self, object ) ) {
  1250. finished();
  1251. return VWFJavaScript.kutility.nodeReference( object.id );
  1252. } else if ( object && object.buffer && object.buffer.toString() === "[object ArrayBuffer]" ) {
  1253. finished();
  1254. return object;
  1255. } else if ( VWFJavaScript.kutility.valueIsNodeReference( object ) ) {
  1256. finished();
  1257. self.logger.warnx( "valueKernelFromJS", "javascript-format value contains a kernel-format node reference" );
  1258. return object;
  1259. } else {
  1260. return object;
  1261. }
  1262. } );
  1263. }
  1264. /// Convert values wrapped by `valueKernelFromJS` into their original form for use in the
  1265. /// JavaScript driver's execution environment.
  1266. ///
  1267. /// This function must run as a method of the driver. Invoke it as:
  1268. /// `valueJSFromKernel.call( driver, value )`.
  1269. ///
  1270. /// @param {Object} value
  1271. ///
  1272. /// @returns {Object}
  1273. static valueJSFromKernel( value ) {
  1274. var self = this;
  1275. return VWFJavaScript.utility.transform( value, function( object, names, depth, finished ) {
  1276. if ( VWFJavaScript.kutility.valueIsNodeReference( object ) ) {
  1277. finished();
  1278. return self.nodes[ object.id ];
  1279. } else if ( object && object.buffer && object.buffer.toString() === "[object ArrayBuffer]" ) {
  1280. finished();
  1281. return object;
  1282. } else if ( VWFJavaScript.valueIsNode.call( self, object ) ) {
  1283. finished();
  1284. self.logger.warnx( "valueJSFromKernel", "kernel-format value contains a javascript-format node reference" );
  1285. return object;
  1286. } else {
  1287. return object;
  1288. }
  1289. } );
  1290. }
  1291. /// Determine if a value is a `model/javascript` node.
  1292. ///
  1293. /// This function must run as a method of the driver. Invoke it as:
  1294. /// `valueIsNode.call( driver, value )`.
  1295. ///
  1296. /// @param {Object} value
  1297. ///
  1298. /// @returns {Boolean}
  1299. static valueIsNode( value ) {
  1300. return this.protoNode && // our proxy for the node.vwf prototype
  1301. ( this.protoNode.isPrototypeOf( value ) || value === this.protoNode );
  1302. }
  1303. }
  1304. /// The `application/javascript` media type for scripts that this driver recognizes.
  1305. ///
  1306. /// @field
  1307. VWFJavaScript.scriptMediaType = "application/javascript";
  1308. /// Regex to crack a `Function.toString()` result.
  1309. ///
  1310. /// @field
  1311. VWFJavaScript.functionRegex = new RegExp(
  1312. "function" + // `function`
  1313. "\\s*" +
  1314. "([a-zA-Z_$][0-9a-zA-Z_$]*)?" + // optional name; capture #1
  1315. "\\s*" +
  1316. "\\(([^)]*)\\)" + // `(...)`; capture #2 inside `()`
  1317. "\\s*" +
  1318. "\\{([^]*)\\}" // `{...}`; capture #3 inside `{}`
  1319. );
  1320. VWFJavaScript.kutility = new KUtility();
  1321. VWFJavaScript.utility = new Utility();
  1322. export { VWFJavaScript as default }