#! /usr/bin/env node
var express = require('express');
var phantom = require('phantom');
var spectre = require('commander');

spectre
    .version('0.1.0')
    .option('-c, --cache', 'Cache files to disk', false)
    .option('-p, --port [port]', 'Port to listen on', parseInt, 9090)
    .option('-h, --host [host]', 'The host to mirror', 'localhost:5000')
    .option('-t, --timeout [seconds]', 'The max amount of time to wait for a page to finish loading', parseInt, 10)
    .parse(process.argv);

var app = express();
var ignoredPaths = ['favicon.ico', '^/static/.+'];
var ignoreRegex = new RegExp(ignoredPaths.map(function(reg) { return '(' + reg + ')';}).join('|'));

var phantomParams = {
    parameters: {
        'load-images': false,
        'disk-cache': !!spectre.cache,
        'local-to-remote-url-access': true
    }
};

function getRenderedHtml(url, callback, page) {
    var status = 200;
    page.set('spectreTimeout', spectre.timeout);

    page.onResourceReceived = function(res) {
        if (res.status > 299 && res.status < 400) return;
        status = res.status;
        page.onResourceReceived = null;
    };

    page.set('onCallback', function() {
        page.get('content', function(content) {
            page.close();
            callback(status, content);
        });
    });

    page.set('onInitialized', function() {
        page.evaluate(function() {
            // setTimeout(window.callPhantom(), page.timeout);
            setTimeout(window.callPhantom(), 10);
            window.callPhantom();
        });
    });

    console.log('requesting url ' + url);
    page.open(url, function(status) {
        if (status === 'failed') {
            console.log('failed to fetch url ' + url);
            callback('');
        }
    });
}

console.log('Spinning up phantomjs instance...');
phantom.create(phantomParams, function(ph) {
    app.get('*', function(req, resp) {
        if (req.url.match(ignoreRegex) !== null) {
            console.log('Redirecting requested resource ' + req.url);
            return resp.redirect('http://' + spectre.host + req.url);
        }

        var url = 'http://' + spectre.host + req.url;
        ph.createPage(getRenderedHtml.bind(this, url, function(status, body) {
            resp.status(status).send(body);
        }));
    });

    console.log('Starting server; listening on port ' + spectre.port + '...');
    app.listen(spectre.port);
});

@@ -1322,17 +1322,18 @@
 ('on
-Initializ
+LoadFinish
 ed',
@@ -1396,11 +1396,8 @@
     
- //
  set
@@ -1435,99 +1435,22 @@
 age.
-timeout);%0A            setTimeout(window.callPhantom(), 10);%0A            window.callPhantom(
+spectreTimeout
 );%0A 

Fix default timeout