javascript.js 72 KB

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