pdfer-upload-imacros
Version:
Upload a pdfer document to the pdfer service using iMacros for Firefox and the PDFer web frontend
1,868 lines (1,624 loc) • 216 kB
JavaScript
;(function(e,t,n,r){function i(r){if(!n[r]){if(!t[r]){if(e)return e(r);throw new Error("Cannot find module '"+r+"'")}var s=n[r]={exports:{}};t[r][0](function(e){var n=t[r][1][e];return i(n?n:e)},s,s.exports)}return n[r].exports}for(var s=0;s<r.length;s++)i(r[s]);return i})(typeof require!=="undefined"&&require,{1:[function(require,module,exports){
var should = require('should')
var readFile = require('imacros-read-file')
var upload = require('../index')
var downloadBase64 = require('download-base64-imacros')
runTests(function (err, reply) {
if (err) {
alert('check test suite fails with error: ' + JSON.stringify(err))
return false
}
iimDisplay('Success! Checks test suite passes')
})
function runTests(cb) {
iimPlay('CODE: TAG POS=1 TYPE=BODY ATTR= EXTRACT=TXT')
var configFilePath = 'file:///users/noah/src/node/docparse/scrapers/imacros/pdfer/login/test/config.json'
loadConfigFile(configFilePath, function (err, config) {
should.not.exist(err, 'error loading config file')
var url = 'file:///users/noah/src/node/docparse/scrapers/imacros/pdfer/upload/test/data/multipage_raw.pdf'
downloadBase64(url, function (err, base64) {
if (err) { return cb(err) }
var data = {
config: config,
base64: base64,
type: 'ocr'
}
upload(data, function (err, responseData) {
if (err) { return cb(err) }
alert('uplaod resData: ' + JSON.stringify(responseData, null, ' '))
cb()
})
})
})
}
function loadConfigFile(filePath, cb) {
readFile(filePath, function (err, reply) {
if (err) { return cb(err) }
var data = JSON.parse(reply)
cb(null, data)
})
}
},{"../index":2,"should":3,"imacros-read-file":4,"download-base64-imacros":5}],2:[function(require,module,exports){
/**
* Get a list of existing bills from the DocParse api server
*/
var rk = require('required-keys');
function getURL(data) {
var config = data.config;
var hash = data.hash;
var email = config.pdfer.email
var password = config.pdfer.password
email = encodeURIComponent(email);
password = encodeURIComponent(password);
var url = 'https://' + email + ':' + password + '@' + config.pdfer.host
+ '/api/sendBase64'
return url;
}
function parseResponse(request, cb) {
var resData;
var statusCode = request.status;
var body = request.response;
if (body === 'Unauthorized') {
iimDisplay('send failed failed, "Unauthorized"');
return cb({
message: 'error uploading file to pdfer service, missing key',
error: 'not authorized',
statusCode: statusCode,
body: body,
file: 'node_modules/pdfer-upload-imacros/index.js'
})
}
try {
resData = JSON.parse(body);
}
catch(err) {
return cb({
message: 'error uploading file to pdfer service, missing key',
error: err,
statusCode: statusCode,
body: body,
file: 'node_modules/pdfer-upload-imacros/index.js'
})
return cb(err);
}
if (statusCode !== 200) {
return cb({
message: 'error uploading file to pdfer service, missing key',
error: 'bad status code',
resData: resData,
statusCode: statusCode,
file: 'node_modules/pdfer-upload-imacros/index.js'
})
}
alert('resData: ' + JSON.stringify(resData, null, ' '))
cb(null, resData);
}
module.exports = function(data, cb) {
var keys = ['config', 'type', 'base64']
var err = rk.truthySync(data, keys)
if (err) {
return cb({
message: 'error uploading file to pdfer service, missing key',
error: err,
file: 'node_modules/pdfer-upload-imacros/index.js'
})
}
var config = data.config
var url = getURL(data);
var type = data.type
var base64 = data.base64
var formData = new FormData();
var xhr = new XMLHttpRequest()
formData.append("base64PDF", base64);
formData.append("type", type);
xhr.open('POST', url, false)
alert('sending to url: ' + url)
xhr.send(formData);
parseResponse(xhr, cb);
};
},{"required-keys":6}],4:[function(require,module,exports){
module.exports = function readFile(filePath, cb) {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", filePath, true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState == 4) {
var text = txtFile.responseText;
return cb(null, text);
}
}
txtFile.send(null)
}
// file:///users/noah/Downloads/dummy.txt
},{}],5:[function(require,module,exports){
module.exports = function (url, cb) {
getImageAsBase64(url, function (base64) {
if (!base64) {
return cb({
message: 'failed to download file at give url',
error: 'base64 string is null',
url: url
})
}
cb(null, base64)
})
}
function getImageAsBase64(imgAddress, cb) {
//get from online or from whatever string store
var req = new XMLHttpRequest()
req.open("GET", imgAddress, true)
req.responseType = 'arraybuffer' //this won't work with sync requests in FF
req.onload = function () {
cb(arrayBufferToDataUri(req.response))
}
req.send(null)
}
function arrayBufferToDataUri(arrayBuffer) {
var base64 = '',
encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
bytes = new Uint8Array(arrayBuffer), byteLength = bytes.byteLength,
byteRemainder = byteLength % 3, mainLength = byteLength - byteRemainder,
a, b, c, d, chunk
for (var i = 0; i < mainLength; i = i + 3) {
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
a = (chunk & 16515072) >> 18; b = (chunk & 258048) >> 12;
c = (chunk & 4032) >> 6; d = chunk & 63;
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
if (byteRemainder == 1) {
chunk = bytes[mainLength];
a = (chunk & 252) >> 2;
b = (chunk & 3) << 4;
base64 += encodings[a] + encodings[b] + '==';
} else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
a = (chunk & 16128) >> 8;
b = (chunk & 1008) >> 4;
c = (chunk & 15) << 2;
base64 += encodings[a] + encodings[b] + encodings[c] + '=';
}
return base64
// return "data:image/jpeg;base64," + base64;
}
},{}],6:[function(require,module,exports){
function keysOnly(data, fields, callback) {
for (var i in fields) {
var key = fields[i];
if (!data.hasOwnProperty(key) || data[key] === undefined) {
var message = 'missing key: ' + key.toString();
if (callback) {
return callback(message, false);
}
return false;
}
}
if (callback) {
return callback(null, true);
}
return true;
}
function nonNull(data, fields, cb) {
var message;
for (var i in fields) {
var key = fields[i];
if (!data.hasOwnProperty(key)) {
message = 'key does not exist in data: ' + key.toString();
if (cb) {
return cb(message, false);
}
return false;
}
if(data[key] === null) {
message = 'value for key is null: ' + key.toString();
if (cb) {
return cb(message, false);
}
return false;
}
if(data[key] === undefined) {
message = 'value for key is undefined: ' + key.toString();
if (cb) {
return cb(message, false);
}
return false;
}
}
if (cb) {
return cb(null, true);
}
return true;
}
function truthy(data, fields, cb) {
var message;
for (var i in fields) {
var key = fields[i];
if (!data.hasOwnProperty(key)) {
message = 'key does not exist in data: ' + key.toString();
if (cb) {
return cb(message, false);
}
return false;
}
if(!data[key]) {
message = 'value for key is falsy: ' + key.toString();
if (cb) {
return cb(message, false);
}
return false;
}
}
if (cb) {
return cb(null, true);
}
return true;
}
/**
* @param {Object} data,
* @param {Array} fields
* @return null if all required keys exist and map to truthy values
* @return {Array} An array containing errors about all keys that failed
*/
function truthySync(data, fields) {
var keys = Object.keys(data);
var errors = [];
var err;
for (var i in fields) {
var key = fields[i];
if (!data.hasOwnProperty(key)) {
err = {
message: 'key not set in data',
key: key,
value: undefined
};
errors.push(err);
}
else if (!data[key]) {
err = {
message: 'value is falsy',
key: key,
value: data[key]
};
errors.push(err);
}
}
if (errors.length === 0) {
return null;
}
return errors;
}
/**
* @param {Object} data,
* @param {Array} fields
* @return null if all required keys exist and map to truthy values
* @return {Array} An array containing errors about all keys that failed
*/
function nonNullSync(data, fields) {
var keys = Object.keys(data);
var errors = [];
var err;
for (var i in fields) {
var key = fields[i];
if (!data.hasOwnProperty(key)) {
err = {
message: 'key not set in data',
key: key,
value: undefined
};
errors.push(err);
}
else if (data[key] === undefined || data[key] === null) {
err = {
message: 'value is null',
key: key,
value: data[key]
};
errors.push(err);
}
}
if (errors.length === 0) {
return null;
}
return errors;
}
/**
* @param {Object} data,
* @param {Array} fields
* @return null if all required keys exist and map to truthy values
* @return {Array} An array containing errors about all keys that failed
*/
function keysOnlySync(data, fields) {
var keys = Object.keys(data);
var errors = [];
var err;
for (var i in fields) {
var key = fields[i];
if (!data.hasOwnProperty(key)) {
err = {
message: 'key not set in data',
key: key,
value: undefined
};
errors.push(err);
}
}
if (errors.length === 0) {
return null;
}
return errors;
}
exports.nonNull = nonNull;
exports.keysOnly = keysOnly;
exports.truthy = truthy;
exports.truthySync = truthySync;
exports.nonNullSync = nonNullSync;
exports.keysOnlySync = keysOnlySync;
},{}],3:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var util = require('util')
, http = require('http')
, assert = require('assert')
, AssertionError = assert.AssertionError
, statusCodes = http.STATUS_CODES
, eql = require('./eql')
, i = util.inspect;
/**
* Expose assert as should.
*
* This allows you to do things like below
* without require()ing the assert module.
*
* should.equal(foo.bar, undefined);
*
*/
exports = module.exports = assert;
/**
* Assert _obj_ exists, with optional message.
*
* @param {Mixed} obj
* @param {String} [msg]
* @api public
*/
exports.exist = exports.exists = function(obj, msg){
if (null == obj) {
throw new AssertionError({
message: msg || ('expected ' + i(obj) + ' to exist')
, stackStartFunction: exports.exist
});
}
};
/**
* Asserts _obj_ does not exist, with optional message.
*
* @param {Mixed} obj
* @param {String} [msg]
* @api public
*/
exports.not = {};
exports.not.exist = exports.not.exists = function(obj, msg){
if (null != obj) {
throw new AssertionError({
message: msg || ('expected ' + i(obj) + ' to not exist')
, stackStartFunction: exports.not.exist
});
}
};
/**
* Expose api via `Object#should`.
*
* @api public
*/
Object.defineProperty(Object.prototype, 'should', {
set: function(){},
get: function(){
return new Assertion(this.valueOf() == this ? this.valueOf() : this);
},
configurable: true
});
/**
* Initialize a new `Assertion` with the given _obj_.
*
* @param {Mixed} obj
* @api private
*/
var Assertion = exports.Assertion = function Assertion(obj) {
this.obj = obj;
};
/**
* Prototype.
*/
Assertion.prototype = {
/**
* HACK: prevents double require() from failing.
*/
exports: exports,
/**
* Assert _expr_ with the given _msg_ and _negatedMsg_.
*
* @param {Boolean} expr
* @param {String} msg
* @param {String} negatedMsg
* @param {Object} expected
* @api private
*/
assert: function(expr, msg, negatedMsg, expected, showDiff){
var msg = this.negate ? negatedMsg : msg
, ok = this.negate ? !expr : expr
, obj = this.obj;
if (ok) return;
var err = new AssertionError({
message: msg.call(this)
, actual: obj
, expected: expected
, stackStartFunction: this.assert
, negated: this.negate
});
err.showDiff = showDiff;
throw err;
},
/**
* Dummy getter.
*
* @api public
*/
get an() {
return this;
},
/**
* Dummy getter.
*
* @api public
*/
get and() {
return this;
},
/**
* Dummy getter.
*
* @api public
*/
get be() {
return this;
},
/**
* Dummy getter.
*
* @api public
*/
get have() {
return this;
},
/**
* Dummy getter.
*
* @api public
*/
get with() {
return this;
},
/**
* Negation modifier.
*
* @api public
*/
get not() {
this.negate = true;
return this;
},
/**
* Get object inspection string.
*
* @return {String}
* @api private
*/
get inspect() {
return i(this.obj);
},
/**
* Assert instanceof `Arguments`.
*
* @api public
*/
get arguments() {
this.assert(
'[object Arguments]' == Object.prototype.toString.call(this.obj)
, function(){ return 'expected ' + this.inspect + ' to be arguments' }
, function(){ return 'expected ' + this.inspect + ' to not be arguments' });
return this;
},
/**
* Assert that an object is empty aka length of 0.
*
* @api public
*/
get empty() {
this.obj.should.have.property('length');
this.assert(
0 === this.obj.length
, function(){ return 'expected ' + this.inspect + ' to be empty' }
, function(){ return 'expected ' + this.inspect + ' not to be empty' });
return this;
},
/**
* Assert ok.
*
* @api public
*/
get ok() {
this.assert(
this.obj
, function(){ return 'expected ' + this.inspect + ' to be truthy' }
, function(){ return 'expected ' + this.inspect + ' to be falsey' });
return this;
},
/**
* Assert true.
*
* @api public
*/
get true() {
this.assert(
true === this.obj
, function(){ return 'expected ' + this.inspect + ' to be true' }
, function(){ return 'expected ' + this.inspect + ' not to be true' });
return this;
},
/**
* Assert false.
*
* @api public
*/
get false() {
this.assert(
false === this.obj
, function(){ return 'expected ' + this.inspect + ' to be false' }
, function(){ return 'expected ' + this.inspect + ' not to be false' });
return this;
},
/**
* Assert equal.
*
* @param {Mixed} val
* @param {String} description
* @api public
*/
eql: function(val, desc){
this.assert(
eql(val, this.obj)
, function(){ return 'expected ' + this.inspect + ' to equal ' + i(val) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not equal ' + i(val) + (desc ? " | " + desc : "") }
, val
, true);
return this;
},
/**
* Assert strict equal.
*
* @param {Mixed} val
* @param {String} description
* @api public
*/
equal: function(val, desc){
this.assert(
val === this.obj
, function(){ return 'expected ' + this.inspect + ' to equal ' + i(val) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not equal ' + i(val) + (desc ? " | " + desc : "") }
, val);
return this;
},
/**
* Assert within start to finish (inclusive).
*
* @param {Number} start
* @param {Number} finish
* @param {String} description
* @api public
*/
within: function(start, finish, desc){
var range = start + '..' + finish;
this.assert(
this.obj >= start && this.obj <= finish
, function(){ return 'expected ' + this.inspect + ' to be within ' + range + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not be within ' + range + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert within value +- delta (inclusive).
*
* @param {Number} value
* @param {Number} delta
* @param {String} description
* @api public
*/
approximately: function(value, delta, description) {
return this.within(value - delta, value + delta, description);
},
/**
* Assert typeof.
*
* @param {Mixed} type
* @param {String} description
* @api public
*/
a: function(type, desc){
this.assert(
type == typeof this.obj
, function(){ return 'expected ' + this.inspect + ' to be a ' + type + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' not to be a ' + type + (desc ? " | " + desc : "") })
return this;
},
/**
* Assert instanceof.
*
* @param {Function} constructor
* @param {String} description
* @api public
*/
instanceof: function(constructor, desc){
var name = constructor.name;
this.assert(
this.obj instanceof constructor
, function(){ return 'expected ' + this.inspect + ' to be an instance of ' + name + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' not to be an instance of ' + name + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert numeric value above _n_.
*
* @param {Number} n
* @param {String} description
* @api public
*/
above: function(n, desc){
this.assert(
this.obj > n
, function(){ return 'expected ' + this.inspect + ' to be above ' + n + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to be below ' + n + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert numeric value below _n_.
*
* @param {Number} n
* @param {String} description
* @api public
*/
below: function(n, desc){
this.assert(
this.obj < n
, function(){ return 'expected ' + this.inspect + ' to be below ' + n + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to be above ' + n + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert string value matches _regexp_.
*
* @param {RegExp} regexp
* @param {String} description
* @api public
*/
match: function(regexp, desc){
this.assert(
regexp.exec(this.obj)
, function(){ return 'expected ' + this.inspect + ' to match ' + regexp + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' not to match ' + regexp + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert property "length" exists and has value of _n_.
*
* @param {Number} n
* @param {String} description
* @api public
*/
length: function(n, desc){
this.obj.should.have.property('length');
var len = this.obj.length;
this.assert(
n == len
, function(){ return 'expected ' + this.inspect + ' to have a length of ' + n + ' but got ' + len + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not have a length of ' + len + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert property _name_ exists, with optional _val_.
*
* @param {String} name
* @param {Mixed} [val]
* @param {String} description
* @api public
*/
property: function(name, val, desc){
if (this.negate && undefined !== val) {
if (undefined === this.obj[name]) {
throw new Error(this.inspect + ' has no property ' + i(name) + (desc ? " | " + desc : ""));
}
} else {
this.assert(
undefined !== this.obj[name]
, function(){ return 'expected ' + this.inspect + ' to have a property ' + i(name) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not have a property ' + i(name) + (desc ? " | " + desc : "") });
}
if (undefined !== val) {
this.assert(
val === this.obj[name]
, function(){ return 'expected ' + this.inspect + ' to have a property ' + i(name)
+ ' of ' + i(val) + ', but got ' + i(this.obj[name]) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not have a property ' + i(name) + ' of ' + i(val) + (desc ? " | " + desc : "") });
}
this.obj = this.obj[name];
return this;
},
/**
* Assert own property _name_ exists.
*
* @param {String} name
* @param {String} description
* @api public
*/
ownProperty: function(name, desc){
this.assert(
this.obj.hasOwnProperty(name)
, function(){ return 'expected ' + this.inspect + ' to have own property ' + i(name) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not have own property ' + i(name) + (desc ? " | " + desc : "") });
this.obj = this.obj[name];
return this;
},
/**
* Assert that `obj` is present via `.indexOf()`.
*
* @param {Mixed} obj
* @param {String} description
* @api public
*/
include: function(obj, desc){
if (obj.constructor == Object){
var cmp = {};
for (var key in obj) cmp[key] = this.obj[key];
this.assert(
eql(cmp, obj)
, function(){ return 'expected ' + this.inspect + ' to include an object equal to ' + i(obj) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not include an object equal to ' + i(obj) + (desc ? " | " + desc : "") });
} else {
this.assert(
~this.obj.indexOf(obj)
, function(){ return 'expected ' + this.inspect + ' to include ' + i(obj) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not include ' + i(obj) + (desc ? " | " + desc : "") });
}
return this;
},
/**
* Assert that an object equal to `obj` is present.
*
* @param {Array} obj
* @param {String} description
* @api public
*/
includeEql: function(obj, desc){
this.assert(
this.obj.some(function(item) { return eql(obj, item); })
, function(){ return 'expected ' + this.inspect + ' to include an object equal to ' + i(obj) + (desc ? " | " + desc : "") }
, function(){ return 'expected ' + this.inspect + ' to not include an object equal to ' + i(obj) + (desc ? " | " + desc : "") });
return this;
},
/**
* Assert that the array contains _obj_.
*
* @param {Mixed} obj
* @api public
*/
contain: function(obj){
console.warn('should.contain() is deprecated, use should.include()');
this.obj.should.be.an.instanceof(Array);
this.assert(
~this.obj.indexOf(obj)
, function(){ return 'expected ' + this.inspect + ' to contain ' + i(obj) }
, function(){ return 'expected ' + this.inspect + ' to not contain ' + i(obj) });
return this;
},
/**
* Assert exact keys or inclusion of keys by using
* the `.include` modifier.
*
* @param {Array|String ...} keys
* @api public
*/
keys: function(keys){
var str
, ok = true;
keys = keys instanceof Array
? keys
: Array.prototype.slice.call(arguments);
if (!keys.length) throw new Error('keys required');
var actual = Object.keys(this.obj)
, len = keys.length;
// make sure they're all present
ok = keys.every(function(key){
return ~actual.indexOf(key);
});
// matching length
ok = ok && keys.length == actual.length;
// key string
if (len > 1) {
keys = keys.map(function(key){
return i(key);
});
var last = keys.pop();
str = keys.join(', ') + ', and ' + last;
} else {
str = i(keys[0]);
}
// message
str = 'have ' + (len > 1 ? 'keys ' : 'key ') + str;
this.assert(
ok
, function(){ return 'expected ' + this.inspect + ' to ' + str }
, function(){ return 'expected ' + this.inspect + ' to not ' + str });
return this;
},
/**
* Assert that header `field` has the given `val`.
*
* @param {String} field
* @param {String} val
* @return {Assertion} for chaining
* @api public
*/
header: function(field, val){
this.obj.should
.have.property('headers').and
.have.property(field.toLowerCase(), val);
return this;
},
/**
* Assert `.statusCode` of `code`.
*
* @param {Number} code
* @return {Assertion} for chaining
* @api public
*/
status: function(code){
this.obj.should.have.property('statusCode');
var status = this.obj.statusCode;
this.assert(
code == status
, function(){ return 'expected response code of ' + code + ' ' + i(statusCodes[code])
+ ', but got ' + status + ' ' + i(statusCodes[status]) }
, function(){ return 'expected to not respond with ' + code + ' ' + i(statusCodes[code]) });
return this;
},
/**
* Assert that this response has content-type: application/json.
*
* @return {Assertion} for chaining
* @api public
*/
get json() {
this.obj.should.have.property('headers');
this.obj.headers.should.have.property('content-type');
this.obj.headers['content-type'].should.include('application/json');
return this;
},
/**
* Assert that this response has content-type: text/html.
*
* @return {Assertion} for chaining
* @api public
*/
get html() {
this.obj.should.have.property('headers');
this.obj.headers.should.have.property('content-type');
this.obj.headers['content-type'].should.include('text/html');
return this;
},
/**
* Assert that this function will or will not
* throw an exception.
*
* @return {Assertion} for chaining
* @api public
*/
throw: function(message){
var fn = this.obj
, err = {}
, errorInfo = ''
, ok = true;
try {
fn();
ok = false;
} catch (e) {
err = e;
}
if (ok) {
if ('string' == typeof message) {
ok = message == err.message;
} else if (message instanceof RegExp) {
ok = message.test(err.message);
} else if ('function' == typeof message) {
ok = err instanceof message;
}
if (message && !ok) {
if ('string' == typeof message) {
errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'";
} else if (message instanceof RegExp) {
errorInfo = " with a message matching " + message + ", but got '" + err.message + "'";
} else if ('function' == typeof message) {
errorInfo = " of type " + message.name + ", but got " + err.constructor.name;
}
}
}
this.assert(
ok
, function(){ return 'expected an exception to be thrown' + errorInfo }
, function(){ return 'expected no exception to be thrown, got "' + err.message + '"' });
return this;
}
};
/**
* Aliases.
*/
(function alias(name, as){
Assertion.prototype[as] = Assertion.prototype[name];
return alias;
})
('instanceof', 'instanceOf')
('throw', 'throwError')
('length', 'lengthOf')
('keys', 'key')
('ownProperty', 'haveOwnProperty')
('above', 'greaterThan')
('below', 'lessThan');
},{"util":7,"http":8,"assert":9,"./eql":10}],7:[function(require,module,exports){
var events = require('events');
exports.isArray = isArray;
exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'};
exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'};
exports.print = function () {};
exports.puts = function () {};
exports.debug = function() {};
exports.inspect = function(obj, showHidden, depth, colors) {
var seen = [];
var stylize = function(str, styleType) {
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
var styles =
{ 'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39] };
var style =
{ 'special': 'cyan',
'number': 'blue',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red' }[styleType];
if (style) {
return '\033[' + styles[style][0] + 'm' + str +
'\033[' + styles[style][1] + 'm';
} else {
return str;
}
};
if (! colors) {
stylize = function(str, styleType) { return str; };
}
function format(value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value !== exports &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
switch (typeof value) {
case 'undefined':
return stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return stylize(simple, 'string');
case 'number':
return stylize('' + value, 'number');
case 'boolean':
return stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return stylize('null', 'null');
}
// Look up the keys of the object.
var visible_keys = Object_keys(value);
var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys;
// Functions without properties can be shortcutted.
if (typeof value === 'function' && keys.length === 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
var name = value.name ? ': ' + value.name : '';
return stylize('[Function' + name + ']', 'special');
}
}
// Dates without properties can be shortcutted
if (isDate(value) && keys.length === 0) {
return stylize(value.toUTCString(), 'date');
}
var base, type, braces;
// Determine the object type
if (isArray(value)) {
type = 'Array';
braces = ['[', ']'];
} else {
type = 'Object';
braces = ['{', '}'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : '';
base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
} else {
base = '';
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + value.toUTCString();
}
if (keys.length === 0) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
return stylize('[Object]', 'special');
}
}
seen.push(value);
var output = keys.map(function(key) {
var name, str;
if (value.__lookupGetter__) {
if (value.__lookupGetter__(key)) {
if (value.__lookupSetter__(key)) {
str = stylize('[Getter/Setter]', 'special');
} else {
str = stylize('[Getter]', 'special');
}
} else {
if (value.__lookupSetter__(key)) {
str = stylize('[Setter]', 'special');
}
}
}
if (visible_keys.indexOf(key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (seen.indexOf(value[key]) < 0) {
if (recurseTimes === null) {
str = format(value[key]);
} else {
str = format(value[key], recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (isArray(value)) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = stylize('[Circular]', 'special');
}
}
if (typeof name === 'undefined') {
if (type === 'Array' && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = stylize(name, 'string');
}
}
return name + ': ' + str;
});
seen.pop();
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.length + 1;
}, 0);
if (length > 50) {
output = braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
} else {
output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
return output;
}
return format(obj, (typeof depth === 'undefined' ? 2 : depth));
};
function isArray(ar) {
return ar instanceof Array ||
Array.isArray(ar) ||
(ar && ar !== Object.prototype && isArray(ar.__proto__));
}
function isRegExp(re) {
return re instanceof RegExp ||
(typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]');
}
function isDate(d) {
if (d instanceof Date) return true;
if (typeof d !== 'object') return false;
var properties = Date.prototype && Object_getOwnPropertyNames(Date.prototype);
var proto = d.__proto__ && Object_getOwnPropertyNames(d.__proto__);
return JSON.stringify(proto) === JSON.stringify(properties);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
exports.log = function (msg) {};
exports.pump = null;
var Object_keys = Object.keys || function (obj) {
var res = [];
for (var key in obj) res.push(key);
return res;
};
var Object_getOwnPropertyNames = Object.getOwnPropertyNames || function (obj) {
var res = [];
for (var key in obj) {
if (Object.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
var Object_create = Object.create || function (prototype, properties) {
// from es5-shim
var object;
if (prototype === null) {
object = { '__proto__' : null };
}
else {
if (typeof prototype !== 'object') {
throw new TypeError(
'typeof prototype[' + (typeof prototype) + '] != \'object\''
);
}
var Type = function () {};
Type.prototype = prototype;
object = new Type();
object.__proto__ = prototype;
}
if (typeof properties !== 'undefined' && Object.defineProperties) {
Object.defineProperties(object, properties);
}
return object;
};
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object_create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (typeof f !== 'string') {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(exports.inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j': return JSON.stringify(args[i++]);
default:
return x;
}
});
for(var x = args[i]; i < len; x = args[++i]){
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + exports.inspect(x);
}
}
return str;
};
},{"events":11}],9:[function(require,module,exports){
(function(){// UTILITY
var util = require('util');
var Buffer = require("buffer").Buffer;
var pSlice = Array.prototype.slice;
function objectKeys(object) {
if (Object.keys) return Object.keys(object);
var result = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
result.push(name);
}
}
return result;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.message = options.message;
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
}
};
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (value === undefined) {
return '' + value;
}
if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
return value.toString();
}
if (typeof value === 'function' || value instanceof RegExp) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (typeof s == 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
assert.AssertionError.prototype.toString = function() {
if (this.message) {
return [this.name + ':', this.message].join(' ');
} else {
return [
this.name + ':',
truncate(JSON.stringify(this.actual, replacer), 128),
this.operator,
truncate(JSON.stringify(this.expected, replacer), 128)
].join(' ');
}
};
// assert.AssertionError instanceof Error
assert.AssertionError.__proto__ = Error.prototype;
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!!!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = objectKeys(a),
kb = objectKeys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (expected instanceof RegExp) {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail('Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail('Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
})()
},{"util":7,"buffer":12}],8:[function(require,module,exports){
var http = module.exports;
var EventEmitter = require('events').EventEmitter;
var Request = require('./lib/request');
http.request = function (params, cb) {
if (!params) params = {};
if (!params.host) params.host = window.location.host.split(':')[0];
if (!params.port) params.port = window.location.port;
var req = new Request(new xhrHttp, params);
if (cb) req.on('response', cb);
return req;
};
http.get = function (params, cb) {
params.method = 'GET';
var req = http.request(params, cb);
req.end();
return req;
};
http.Agent = function () {};
http.Agent.defaultMaxSockets = 4;
var xhrHttp = (function () {
if (typeof window === 'undefined') {
throw new Error('no window object present');
}
else if (window.XMLHttpRequest) {
return window.XMLHttpRequest;
}
else if (window.ActiveXObject) {
var axs = [
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.3.0',
'Microsoft.XMLHTTP'
];
for (var i = 0; i < axs.length; i++) {
try {
var ax = new(window.ActiveXObject)(axs[i]);
return function () {
if (ax) {
var ax_ = ax;
ax = null;
return ax_;
}
else {
return new(window.ActiveXObject)(axs[i]);
}
};
}
catch (e) {}
}
throw new Error('ajax not supported in this browser')
}
else {
throw new Error('ajax not supported in this browser');
}
})();
},{"events":11,"./lib/request":13}],14:[function(require,module,exports){
require=(function(e,t,n,r){function i(r){if(!n[r]){if(!t[r]){if(e)return e(r);throw new Error("Cannot find module '"+r+"'")}var s=n[r]={exports:{}};t[r][0](function(e){var n=t[r][1][e];return i(n?n:e)},s,s.exports)}return n[r].exports}for(var s=0;s<r.length;s++)i(r[s]);return i})(typeof require!=="undefined"&&require,{1:[function(require,module,exports){
// UTILITY
var util = require('util');
var Buffer = require("buffer").Buffer;
var pSlice = Array.prototype.slice;
function objectKeys(object) {
if (Object.keys) return Object.keys(object);
var result = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
result.push(name);
}
}
return result;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
//