4 AFB = function(base, initialtoken){
6 urlws = "ws://"+window.location.host+"/"+base;
7 urlhttp = "http://"+window.location.host+"/"+base;
9 /*********************************************/
11 /**** AFB_context ****/
13 /*********************************************/
17 var TOKEN = initialtoken;
19 var context = function(token, uuid) {
25 get token() {return TOKEN;},
26 set token(tok) {if(tok) TOKEN=tok;},
27 get uuid() {return UUID;},
28 set uuid(id) {if(id) UUID=id;}
31 AFB_context = new context();
33 /*********************************************/
35 /**** AFB_websocket ****/
37 /*********************************************/
45 var PROTO1 = "x-afb-ws-json1";
47 AFB_websocket = function(onopen, onabort) {
49 if (AFB_context.token) {
50 u = u + '?x-afb-token=' + AFB_context.token;
52 u = u + '&x-afb-uuid=' + AFB_context.uuid;
54 this.ws = new WebSocket(u, [ PROTO1 ]);
58 this.ws.onopen = onopen.bind(this);
59 this.ws.onerror = onerror.bind(this);
60 this.ws.onclose = onclose.bind(this);
61 this.ws.onmessage = onmessage.bind(this);
63 this.onabort = onabort;
64 this.onclose = onabort;
67 function onerror(event) {
74 this.onerror && this.onerror(this);
77 function onopen(event) {
84 function onclose(event) {
85 for (var id in this.pendings) {
86 var ferr = this.pendings[id].onerror;
87 ferr && ferr(null, this);
90 this.onclose && this.onclose();
93 function fire(awaitens, name, data) {
94 var a = awaitens[name];
96 a.forEach(function(handler){handler(data);});
97 var i = name.indexOf("/");
99 a = awaitens[name.substring(0,i)];
101 a.forEach(function(handler){handler(data);});
105 a.forEach(function(handler){handler(data);});
108 function reply(pendings, id, ans, offset) {
109 if (id in pendings) {
110 var p = pendings[id];
117 function onmessage(event) {
118 var obj = JSON.parse(event.data);
122 AFB_context.token = obj[3];
125 reply(this.pendings, id, ans, 0);
128 reply(this.pendings, id, ans, 1);
132 fire(this.awaitens, id, ans);
142 function call(method, request) {
143 return new Promise((function(resolve, reject){
146 id = String(this.counter = 4095 & (this.counter + 1));
147 } while (id in this.pendings);
148 this.pendings[id] = [ resolve, reject ];
149 arr = [CALL, id, method, request ];
150 if (AFB_context.token) arr.push(AFB_context.token);
151 this.ws.send(JSON.stringify(arr));
155 function onevent(name, handler) {
157 var list = this.awaitens[id] || (this.awaitens[id] = []);
161 AFB_websocket.prototype = {
167 /*********************************************/
171 /*********************************************/
173 context: AFB_context,