jim / diligence

A tiny remote JavaScript console/test runner built with Node

This URL has Read+Write access

diligence / diligence.js
100644 231 lines (190 sloc) 5.87 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
exports.diligence = {};
 
exports.diligence.Server = function(setupCallback) {
  var browsers = [], files = [];
  var config = {};
  setupCallback(config);
  applyDefaults(config);
  
  start();
  
  function start() {
    var server = new node.http.Server(function (req, res) {
 
        debug('Processing request: ' + req.uri.path);
 
        if (req.uri.path == '/result') {
          req.setBodyEncoding('utf8');
          var body = '';
          req.onBody = function (chunk) {
            body += chunk;
          };
          req.onBodyComplete = function() {
            return result(body, req, res);
          };
        } else if (req.uri.path == '/tick') {
          return tick(req, res);
        } else if (match = req.uri.path.match(/^\/file/)){
          return sendFile(req.uri.params.path, res);
        } else if (match = req.uri.path.match(/^\/static\/(.*)/)){
          return sendStaticFile(match[1], res);
        } else {
          return boot(req, res);
        }
 
      }).listen(config['port']);
 
    if (server) {
      puts("diligence is running on port " + config['port'].toString() + ".");
    }
  }
  
  function debug(object) {
    if (config.debug) {
      if(typeof(object) == 'string') {
        puts(object);
      } else {
        for (var key in object) {
          puts(key + ": " + object[key]);
        }
      }
    }
  }
  
  function applyDefaults(config) {
    var defaults = {
      debug: false,
      publicPath: 'public',
      port: 5678,
      testPaths: [],
      collectPath: ''
    }
    
    for (var key in defaults) {
      if (typeof(config[key]) == 'undefined') {
        config[key] = defaults[key];
      }
    }
    
    if (typeof(config.runnerPath) == 'undefined') {
      config.runnerPath = publicPath('runner.html');
    }
    
  }
 
  function getUA(req) {
    var headers = req.headers;
    for (var i=0,l=headers.length; i<l; i++) {
      if (headers[i][0] == 'User-Agent') {
        return headers[i][1];
      }
    }
  }
 
  function getBrowserName(req) {
    var ua = getUA(req);
    
    try {
      if (ua.match(/Chrome/)) {
        return 'Chrome ' + ua.match(/Chrome\/([\d\.]+)/)[1];
      } else if (ua.match(/Firefox/)) {
        return 'Firefox ' + ua.match(/Firefox\/([\d\.]+)/)[1];
      } else if (ua.match(/Safari/)) {
        return 'Safari ' + ua.match(/Version\/([^ ]+) Safari\/528.17/)[1];
      } else if (ua.match(/Opera/)) {
        return 'Opera ' + ua.match(/Opera\/([\d\.]+)/)[1];
      }
    } catch(e) {
      
    }
    
    return ua;
  }
 
  function getBrowserState(req) {
    var ua = getUA(req);
    for (var i=0,l=browsers.length; i<l; i++) {
      if (browsers[i][0] == ua) {
        debug('found ' + ua);
        return browsers[i][1];
      }
    }
    var status = {};
    browsers.push([ua, status]);
    debug('adding ' + ua);
    return status;
  }
 
  // path and file handling
  
  function expandPaths(paths) {
    if (typeof(paths) == 'string') { paths = [paths] }
    
    var pathList = [];
    for (var i=0,l=paths.length; i<l; i++) {
      pathList.push(paths[i]);
    }
    return pathList;
  }
 
 
  function publicPath(path) {
    return config.publicPath + '/' + path;
  }
 
  function loadUtfFile(path, callback) {
    node.fs.stat(path, function(status, stats) {
      var size = stats['size'];
      var file = new node.fs.File({encoding: 'utf8'});
      file.open(path, "r+");
      file.read(size, 0, function(data) {
        callback(data);
      });
    });
  }
 
  // responses
 
  function sendNothing(res) {
    res.sendHeader(200, []);
    res.finish();
  }
 
  function sendData(data, contentType, res) {
    res.sendHeader(200, [["Content-Type", contentType]]);
    res.sendBody(data);
    res.finish();
  }
 
  function sendStaticFile(filename, res) {
    sendFile(publicPath(filename), res);
  }
 
  function sendFile(path, res) {
    debug("serving file '" + path + "'");
    var extension = path.match(/.*(js|html)$/)[1];
    var contentType = extension == 'js' ? 'text/javascript' : 'text/html';
    loadUtfFile(path, function(data) {
      sendData(data, contentType, res);
    });
  }
 
  // actions
 
  function result(body, req, res) {
    var result = JSON.parse(body);
    var browser = {
      userAgent: getUA(req),
      name: getBrowserName(req)
    };
    config.process(browser, result.data);
    sendNothing(res);
  }
 
  function boot(req, res) {
    
    var browser = getBrowserState(req);
    browser.lastSeenAt = new Date().getTime();
    
    var html = loadUtfFile(config.runnerPath, function(data) {
      var scripts = '';
      var paths = expandPaths(config.testPaths);
 
      paths.unshift(publicPath('runner.js'));
      paths.unshift(publicPath('ajax.js'));
      paths.unshift(publicPath('json2.js'));
      
      for (var i=0,l=paths.length; i<l; i++) {
        scripts += '<script type="text/javascript" src="/files?path=' + encodeURIComponent(paths[i]) + '"></script>' + "\n"
      }
      
      var page = data.replace('</head>', scripts + '</head>');
      sendData(page, 'text/html', res);
    });
  }
 
  function tick(req, res) {
 
    var paths = expandPaths(config.testPaths);
    var fileContent = '';
    var browser = getBrowserState(req);
    var now = new Date().getTime();
    
    function checkModTime(index) {
      node.fs.stat(paths[index], function(status, stats) {
        if (typeof(browser.lastSeenAt) == 'undefined' || browser.lastSeenAt < stats['mtime'].getTime()) {
          browser.lastSeenAt = now;
          sendData(JSON.stringify({reload: true}), 'text/javascript', res);
        } else {
          var nextIndex = index + 1;
          if (nextIndex < paths.length) {
            checkModTime(nextIndex);
          } else {
            sendData(JSON.stringify({reload: false}), 'text/javascript', res);
          }
        }
      });
    }
    checkModTime(0);
  }
  
};