javascript.js 72 KB

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