This commit is contained in:
Dobie Wollert
2015-12-16 09:12:35 -08:00
parent f9c9672818
commit f94ca33b9e
805 changed files with 67409 additions and 24609 deletions

View File

@ -1,42 +0,0 @@
var mongoose = require('mongoose'),
Clock = mongoose.model('Clock');
module.exports = function(piler) {
return {
index: function(req, res, next) {
host = String(req.headers['x-forwarded-host']);
host = host.split(':')[0];
if (host != 'clock.atlb.co') {
return next();
}
if (!req.user) {
req.session.redirectUrl = req.url
}
var path = req.path.slice(1);
res.render('clock.jade', {
css: piler.css.renderTags()
});
},
post: function(req, res) {
var clock = new Clock({
tech: req.user,
action: req.body.action,
lat: req.body.lat,
long: req.body.long,
dt: new Date()
});
clock.save(function(err, result) {
if (err) {
return res.json(500, err);
} else {
res.json(result);
}
});
}
}
}

64
app/controllers/db.js Normal file
View File

@ -0,0 +1,64 @@
var mongoose = require('mongoose');
var TimeClockSpan = mongoose.model('TimeClockSpan');
var Workorder = mongoose.model('Workorder');
var db = {};
db.spans = {
forWeek: function(week) {
const startOfWeek = week.clone();
const endOfWeek = week.clone().endOf('week');
const query = {
start: {
$gte: startOfWeek,
$lte: endOfWeek
}
};
return TimeClockSpan.find(query);
},
forWeekByUser: function(week, user) {
const startOfWeek = week.clone();
const endOfWeek = week.clone().endOf('week');
const query = {
start: {
$gte: startOfWeek,
$lte: endOfWeek
},
user: user
};
return TimeClockSpan.find(query);
}
};
db.workorders = {
findByIds: function(ids) {
const query = {
_id: {
$in: ids
}
};
return Workorder.find(query);
}
};
module.exports = db;
function findWorkordersById(ids) {
const query = {
_id: {
$in: ids
}
};
return Workorder
.find(query)
.populate('client', 'name identifier')
.exec();
}

View File

@ -155,9 +155,9 @@ function getPmsByDate(year, month) {
];
}
return Workorder.aggregateAsync(pipeline)
return Workorder.aggregate(pipeline)
.exec()
.then(function(pmsData) {
var data = {};
if (month !== undefined) {
@ -183,12 +183,13 @@ function getPmsByDate(year, month) {
}
function getClients() {
return Client.find({ deleted: false })
return Client
.find({ deleted: false })
.lean()
.select('name identifier frequencies')
.slice('contacts', 1)
.sort('name')
.execAsync();
.exec();
}
function filterClientsByFrequency(month, frequency) {

View File

@ -5,11 +5,25 @@ var moment = require('moment-timezone');
var _ = require('lodash');
var Promise = require('bluebird');
var TimeClockSpan = mongoose.model('TimeClockSpan');
var TimeClockException = mongoose.model('TimeClockException');
var Workorder = mongoose.model('Workorder');
var email = require('../util/email');
var config = require('../../config/config')['prod'];
var NON_BILLABLES = ['shop', 'break', 'pto', 'meeting', 'event', 'weather', 'holiday'];
var TASK_TYPES = ['workday', 'workorder', 'nonBillable'];
var exceptionTemplate = email.template(
'exception.html.tmpl',
'exception.text.tmpl',
'Exception',
[
'techName',
'date',
'message'
]
);
function MultipleSpansError(spans) {
Error.captureStackTrace(this, MultipleSpansError);
@ -20,15 +34,15 @@ function MultipleSpansError(spans) {
MultipleSpansError.prototype = Object.create(Error.prototype);
function findUserSpans(user, day) {
var startOfDay = day.clone().startOf('day').utc().toDate();
var endOfDay = day.clone().endOf('day').utc().toDate();
var startOfDay = day.clone().startOf('day').toDate();
var endOfDay = day.clone().endOf('day').toDate();
var query = {
start: {
'$gte': startOfDay,
'$lte': endOfDay
},
user: user.id
user: user
};
return TimeClockSpan
@ -79,7 +93,7 @@ function filterSpans(spans, filter) {
};
return _.chain(spans)
.filter(function(span) {
.filter(function (span) {
if (filter.type && filter.type.indexOf(span.type) === -1) {
return false;
@ -109,7 +123,7 @@ function spansStatus(spans, filter) {
}
var result = 'pending';
_.forEach(spans, function(span) {
_.forEach(spans, function (span) {
if (span.status === 'open') {
result = 'clockedIn';
return false;
@ -180,7 +194,7 @@ function handleStatusRequest(spans, workorders) {
var results = {};
var workdaySpans = _.filter(spans, { type: 'workday' });
var workdaySpans = _.filter(spans, {type: 'workday'});
results.tasks = [];
@ -192,8 +206,8 @@ function handleStatusRequest(spans, workorders) {
results.tasks = results.tasks.concat(_.chain(workorders)
.sortBy('scheduling.start')
.map(function(workorder) {
var workorderSpans = filterSpans(spans, { type: 'workorder', workorder: workorder.id });
.map(function (workorder) {
var workorderSpans = filterSpans(spans, {type: 'workorder', workorder: workorder.id});
return {
type: 'workorder',
@ -209,8 +223,8 @@ function handleStatusRequest(spans, workorders) {
);
results.tasks = results.tasks.concat(_.chain(NON_BILLABLES)
.map(function(nonBillable) {
var nonBillableSpans = filterSpans(spans, { reason: nonBillable });
.map(function (nonBillable) {
var nonBillableSpans = filterSpans(spans, {reason: nonBillable});
return {
type: 'nonBillable',
@ -226,7 +240,7 @@ function handleStatusRequest(spans, workorders) {
}
function handleClockInRequest(params, user, spans, workorders, now) {
var workdayStatus = spansStatus(spans, { type: 'workday' });
var workdayStatus = spansStatus(spans, {type: 'workday'});
if (params.type === 'workday') {
if (workdayStatus === 'clockedIn') {
@ -284,7 +298,7 @@ function handleClockInRequest(params, user, spans, workorders, now) {
function handleClockInExceptions(user, workorder, spans, now) {
var closedWorkordersSpans = filterSpans(spans, { type: 'workorder', status: 'closed' });
var closedWorkordersSpans = filterSpans(spans, {type: 'workorder', status: 'closed'});
var isFirstWorkorder = closedWorkordersSpans.length == 0;
if (isFirstWorkorder) {
@ -292,6 +306,13 @@ function handleClockInExceptions(user, workorder, spans, now) {
var minutes = now.diff(start, 'minutes');
if (minutes > 15) {
new TimeClockException({
user: user._id,
date: new Date(),
reason: 'late_to_first_workorder'
}).save();
reportException({
user: user,
workorder: workorder,
@ -309,6 +330,12 @@ function handleClockInExceptions(user, workorder, spans, now) {
console.log("Time between tasks: ", minutes);
if (minutes < 5) {
new TimeClockException({
user: user._id,
date: new Date(),
reason: 'too_little_travel'
}).save();
reportException({
user: user,
workorder: workorder,
@ -317,6 +344,12 @@ function handleClockInExceptions(user, workorder, spans, now) {
}
if (minutes > 75) {
new TimeClockException({
user: user._id,
date: new Date(),
reason: 'too_much_travel'
}).save();
reportException({
user: user,
workorder: workorder,
@ -328,13 +361,24 @@ function handleClockInExceptions(user, workorder, spans, now) {
}
function reportException(exception) {
// TODO: Actually send emails for exceptions.
console.log('--- EXCEPTION ---', exception.reason);
const message = {
to: config.email.exception
};
const values = {
techName: `${exception.user.name.first} ${exception.user.name.last}`,
date: moment().format('LLLL'),
message: exception.reason
};
email.send(message, exceptionTemplate, values);
console.log('--- EXCEPTION ---', new Date(), exception.reason);
}
function handleClockOutRequest(params, user, spans, workorders, now) {
var workdaySpans = filterSpans(spans, { type: 'workday' });
var workdaySpans = filterSpans(spans, {type: 'workday'});
var workdayStatus = spansStatus(workdaySpans);
if (workdayStatus !== 'clockedIn') {
@ -356,7 +400,7 @@ function handleClockOutRequest(params, user, spans, workorders, now) {
return Promise.reject('Invalid workorder');
}
var workorderSpans = filterSpans(spans, { type: 'workorder', workorder: workorder.id });
var workorderSpans = filterSpans(spans, {type: 'workorder', workorder: workorder.id});
var workorderStatus = spansStatus(workorderSpans);
if (workorderStatus !== 'clockedIn') {
@ -367,7 +411,7 @@ function handleClockOutRequest(params, user, spans, workorders, now) {
}
if (params.type === 'nonBillable') {
var nonBillableSpans = filterSpans(spans, { type: 'nonBillable', reason: params.reason });
var nonBillableSpans = filterSpans(spans, {type: 'nonBillable', reason: params.reason});
var nonBillableStatus = spansStatus(nonBillableSpans);
if (nonBillableStatus !== 'clockedIn') {
@ -389,7 +433,7 @@ function handleWorkorderDetailsRequest(params, user, spans, workorder, today) {
return Promise.reject('Invalid workorder');
}
var workorderSpans = filterSpans(spans, { type: 'workorder', workorder: workorder.id });
var workorderSpans = filterSpans(spans, {type: 'workorder', workorder: workorder.id});
var workorderStatus = spansStatus(workorderSpans);
workorder = workorder.toObject();
@ -405,7 +449,7 @@ function handleWorkorderDetailsRequest(params, user, spans, workorder, today) {
};
if (workorderStatus != 'clockedIn') {
var workdayStatus = spansStatus(spans, { type: 'workday' });
var workdayStatus = spansStatus(spans, {type: 'workday'});
var otherSpansStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']});
if (workdayStatus != 'clockedIn' || otherSpansStatus == 'clockedIn') {
@ -433,13 +477,13 @@ function ensureSingularSpan(spans) {
}
function responseHandler(res) {
return function(data) {
return function (data) {
res.json(data);
};
}
function errorHandler(res) {
return function(error) {
return function (error) {
if (typeof error === 'string') {
res.json(400, {
error: {
@ -453,15 +497,39 @@ function errorHandler(res) {
};
}
module.exports = function() {
function validateUserId(req) {
const id = req.param('user_id');
if (!id) {
return Promise.reject("Parameter missing 'user_id'");
}
return Promise.resolve(id);
}
function validateDate(req, field) {
let date = req.param(field);
if (!date) {
return Promise.reject(`Parameter '${field}' is required.`);
}
date = moment(date, 'YYYY-MM-DD');
if (!date.isValid()) {
return Promise.reject(`Parameter '${field}' is not a valid date.`)
}
return Promise.resolve(date);
}
module.exports = function () {
return {
index: function(req, res) {
index: function (req, res) {
//TODO: Check to make sure user has a valid timesheet.
var today = moment();
var spans = findUserSpans(req.user, today);
var spans = findUserSpans(req.user.id, today);
var workorders = findUserWorkorders(req.user, today);
Promise.join(spans, workorders, handleStatusRequest)
@ -469,14 +537,14 @@ module.exports = function() {
.catch(errorHandler(res));
},
clockIn: function(req, res) {
clockIn: function (req, res) {
//TODO: Check to make sure user has a valid timesheet.
var today = moment();
var params = validateClockRequest(req);
var spans = findUserSpans(req.user, today);
var spans = findUserSpans(req.user.id, today);
var workorders = findUserWorkorders(req.user, today);
Promise.join(params, req.user, spans, workorders, today, handleClockInRequest)
@ -484,27 +552,42 @@ module.exports = function() {
.catch(errorHandler(res));
},
clockOut: function(req, res) {
clockOut: function (req, res) {
//TODO: Check to make sure user has a valid timesheet.
var today = moment();
var params = validateClockRequest(req);
var spans = findUserSpans(req.user, today);
var workorders = findUserWorkorders(req.user, today);
Promise.join(params, req.user, spans, workorders, today, handleClockOutRequest)
Promise
.props({
id: req.user.id,
date: moment(),
notes: req.body.notes
})
.then((params) => {
var spans = findUserSpans(req.user.id, params.date);
var workorders = findUserWorkorders(req.user, params.date);
return Promise.join(params, req.user, spans, workorders, params.date, handleClockOutRequest);
})
.then(responseHandler(res))
.catch(errorHandler(res));
},
workorderDetails: function(req, res) {
spansForUser: function (req, res) {
Promise
.props({
id: validateUserId(req),
date: validateDate(req, 'date')
})
.then((params) => findUserSpans(params.id, params.date))
.then(responseHandler(res))
.catch(errorHandler(res));
},
workorderDetails: function (req, res) {
var today = moment();
validateWorkorderDetailsRequest(req)
.then(function(params) {
.then(function (params) {
var spans = findUserSpans(req.user, today);
var workorder = findUserWorkorder(params.id, req.user);
@ -512,9 +595,7 @@ module.exports = function() {
})
.then(responseHandler(res))
.catch(errorHandler(res));
},
Promise.join
}
}
};

View File

@ -0,0 +1,370 @@
"use strict";
var mongoose = require('mongoose');
var moment = require('moment-timezone');
var _ = require('lodash');
var Promise = require('bluebird');
var TimeClockSpan = mongoose.model('TimeClockSpan');
var Workorder = mongoose.model('Workorder');
var User = mongoose.model('User');
var db = require('./db');
const NON_BILLABLE_WORKORDER_TYPES = [
'shop', 'break', 'pto', 'meeting', 'event', 'weather'
];
const PAYROLL_WORKORDER_TYPE_MAP = {
'office': 'office',
'anesthesia': 'anesthesia',
'biomed': 'biomed',
'bsp': 'bsp',
'ice': 'ice',
'imaging': 'other',
'sales': 'sales',
'sterile-processing': 'sterilizer',
'depot': 'depot',
'trace-gas': 'other',
'room-air-exchange': 'other',
'isolation-panels': 'electric',
'ups-systems': 'electric',
'relocation': 'other',
'ice-maker': 'other',
'waste-management-system': 'other',
'medgas': 'other',
'staffing': 'other',
'ert': 'electric',
'shop': 'non-billable',
'break': 'non-billable',
'pto': 'non-billable',
'meeting': 'non-billable',
'event': 'non-billable',
'weather': 'non-billable',
'legacy': 'legacy'
};
function findUserDaysWorked(id) {
var query = {
user: id,
type: 'workday',
status: 'closed'
};
return TimeClockSpan
.find(query).exec()
.then((records) => _.chain(records).reduce(accumulateDaysWorked, {}).values())
}
function accumulateDaysWorked(result, record) {
const date = moment(record.start).local().startOf('day').format('YYYY-MM-DD');
if (!result[date]) {
result[date] = {
date: date,
duration: 0
};
}
if (record.duration) {
result[date].duration += record.duration;
}
return result;
}
function responseHandler(res) {
return function (data) {
res.json(data);
};
}
function errorHandler(res) {
return function (error) {
if (typeof error === 'string') {
res.json(400, {
error: {
message: error
}
});
} else {
console.error(error.stack);
res.json(500, 'Internal error');
}
};
}
function validateUserId(req) {
const id = req.param('user_id');
if (!id) {
return Promise.reject("Parameter missing 'user_id'");
}
return Promise.resolve(id);
}
function validateWeek(req) {
let week = req.param('week');
if (!week) {
return Promise.reject("Parameter 'week' is required.");
}
week = moment(week, 'YYYY-MM-DD');
if (!week.isValid()) {
return Promise.reject("Parameter 'week' is not a valid date.")
}
if (week.weekday() !== 0) {
return Promise.reject("Parameter 'week' does not start at the beginning of the week (Sunday).");
}
// Return as string.
return Promise.resolve(week);
}
function summaryHandler(params) {
const spans = findAllSpansForWeek(params.week);
return buildReport(spans);
}
function userSummaryHandler(params) {
const spans = findUserSpansForWeek(params.id, params.week);
return buildReport(spans);
}
function buildReport(spans) {
const workordersById = spans
.then(extractIds('workorder'))
.then(findWorkordersById)
.then(indexById);
const usersById = spans
.then(extractIds('user'))
.then(findUsersById)
.then(indexById);
return Promise.join(spans, workordersById, usersById, generateSummary);
}
function generateSummary(spans, workordersById, usersById) {
var results = {};
function fetchOrCreateUserRecord(userId) {
var record = results[userId];
if (!record) {
var user = usersById[userId];
record = results[userId] = {
user: {
_id: user._id,
name: user.name
},
hasOpenSpans: false,
workorders: {},
spans: {},
clockedTime: 0,
workedTime: 0,
accountingByWorkorder: {},
accountingByWorkorderType: {},
accountingByPayroll: {},
accountingByNonBillable: {},
};
}
return record;
}
function addWorkorder(user, workorder) {
if (!user.workorders[workorder.id]) {
user.workorders[workorder.id] = {
_id: workorder._id,
client: workorder.client,
biomedId: workorder.biomedId,
reason: workorder.reason
}
}
}
function logTime(collection, key, duration) {
if (!collection[key]) {
collection[key] = {
type: key,
duration: duration
}
} else {
collection[key].duration += duration;
}
}
_.forEach(spans, (span) => {
var user = fetchOrCreateUserRecord(span.user);
user.spans[span._id] = span.toObject();
delete user.spans[span._id].__v;
delete user.spans[span._id].user;
if (span.status !== 'closed') {
user.hasOpenSpans = true;
return;
}
if (span.type === 'workday') {
user.clockedTime += span.duration;
}
if (span.type === 'workorder') {
user.workedTime += span.duration;
var workorder = workordersById[span.workorder];
var workorderType = workorder.workorderType;
// If workorder is actually a non-billable (Stupid), treat it as such...
if (NON_BILLABLE_WORKORDER_TYPES.indexOf(workorderType) > -1) {
logTime(user.accountingByNonBillable, workorderType, span.duration);
} else {
addWorkorder(user, workorder);
logTime(user.accountingByWorkorderType, workorderType, span.duration);
logTime(user.accountingByPayroll, PAYROLL_WORKORDER_TYPE_MAP[workorderType], span.duration);
logTime(user.accountingByWorkorder, span.workorder, span.duration);
}
}
if (span.type === 'nonBillable') {
user.workedTime += span.duration;
logTime(user.accountingByNonBillable, span.reason, span.duration);
}
});
_.forEach(results, (user) => {
user.travelTime = Math.max(0, user.clockedTime - user.workedTime);
user.spans = _.values(user.spans);
user.accountingByWorkorder = _.values(user.accountingByWorkorder);
user.accountingByWorkorderType = _.values(user.accountingByWorkorderType);
user.accountingByPayroll = _.values(user.accountingByPayroll);
user.accountingByNonBillable = _.values(user.accountingByNonBillable);
});
return _.values(results);
}
function extractIds(field) {
return (data) => _(data)
.pluck(field)
.reject(_.isUndefined)
.uniq((id) => id.toString())
.value();
}
function indexById(data) {
return _.indexBy(data, 'id')
}
function findWorkordersById(ids) {
const query = {
_id: {
$in: ids
}
};
return Workorder
.find(query)
.populate('client', 'name identifier')
.exec();
}
function findUsersById(ids) {
const query = {
_id: {
$in: ids
}
};
return User.find(query).exec();
}
function findAllSpansForWeek(week) {
var startOfWeek = week.clone().startOf('week');
var endOfWeek = week.clone().endOf('week');
console.log(`Finding spans between ${startOfWeek.format()} and ${endOfWeek.format()}`);
var query = {
start: {
'$gte': startOfWeek.toDate(),
'$lte': endOfWeek.toDate()
}
};
return TimeClockSpan.find(query).exec();
}
function findUserSpansForWeek(id, week) {
var startOfWeek = week.clone().startOf('week');
var endOfWeek = week.clone().endOf('week');
console.log(`Finding spans between ${startOfWeek.format()} and ${endOfWeek.format()}`);
var query = {
start: {
'$gte': startOfWeek.toDate(),
'$lte': endOfWeek.toDate()
},
user: id
};
return TimeClockSpan.find(query).exec();
}
module.exports = function () {
return {
daysWorked: function (req, res) {
req.check('user_id').notEmpty().isMongoId();
var errors = req.validationErrors();
if (errors) {
return res.json(400, errors);
}
var params = {
id: req.param('user_id')
};
findUserDaysWorked(params.id)
.then(responseHandler(res))
.catch(errorHandler(res));
},
summary: function (req, res) {
req.check('week').notEmpty().isWeek();
var errors = req.validationErrors();
if (errors) {
return res.json(400, errors);
}
var params = {
week: moment(req.sanitize('week'))
};
summaryHandler(params)
.then(responseHandler(res))
.catch(errorHandler(res));
},
userSummary: function (req, res) {
Promise
.props({
id: validateUserId(req),
week: validateWeek(req)
})
.then(userSummaryHandler)
.then(responseHandler(res))
.catch(errorHandler(res));
}
}
};

View File

@ -1,4 +1,3 @@
var mongoose = require('mongoose'),
async = require('async'),
User = mongoose.model('User'),
@ -6,20 +5,20 @@ var mongoose = require('mongoose'),
var log = require('log4node');
module.exports = function(config, directory) {
module.exports = function (config, directory) {
function fetch_all_users(callback) {
async.parallel({
gapps: directory.listUsers,
local: function(callback) {
User.find({ deleted: false }).select('name email groups perms deleted').exec(callback);
local: function (callback) {
User.find({deleted: false}).select('name email groups perms deleted').exec(callback);
}
}, callback);
}
function map_local_users(data, results) {
return function(callback) {
async.each(data, function(item, callback) {
return function (callback) {
async.each(data, function (item, callback) {
var key = item.email.toLowerCase();
if (blacklist.indexOf(key) == -1)
@ -32,8 +31,8 @@ module.exports = function(config, directory) {
}
function map_gapps_users(data, results) {
return function(callback) {
async.each(data, function(item, callback) {
return function (callback) {
async.each(data, function (item, callback) {
var key = item.primaryEmail.toLowerCase();
// Ignore if blacklisted
@ -43,8 +42,8 @@ module.exports = function(config, directory) {
results[key] = {
email: item.primaryEmail,
deleted: false,
perms: [ ],
groups: [ ],
perms: [],
groups: [],
name: {
first: item.name.givenName,
last: item.name.familyName
@ -58,12 +57,12 @@ module.exports = function(config, directory) {
}
function reduce_array(data, results) {
return function(callback) {
return function (callback) {
for (var item in data) {
results.push(data[item]);
}
results.sort(function(a, b) {
results.sort(function (a, b) {
var result = a.name.first.toLowerCase().localeCompare(b.name.first.toLowerCase());
if (result == 0)
result = a.name.last.toLowerCase().localeCompare(b.name.last.toLowerCase());
@ -84,14 +83,14 @@ module.exports = function(config, directory) {
map_gapps_users(data.gapps.users, map),
reduce_array(map, reduce),
],
function(err) {
function (err) {
callback(err, reduce);
});
}
return {
index: function(req, res) {
var criteria = { deleted: false };
index: function (req, res) {
var criteria = {deleted: false};
if (req.query.group) {
criteria.groups = req.query.group;
@ -107,7 +106,7 @@ module.exports = function(config, directory) {
var query = User.find(criteria)
.select('name groups')
.exec(function(err, results) {
.exec(function (err, results) {
if (err) {
res.json(500, err);
} else {
@ -116,19 +115,19 @@ module.exports = function(config, directory) {
});
},
details: function(req, res) {
details: function (req, res) {
async.waterfall([
fetch_all_users,
merge_sources,
],
function(err, results) {
function (err, results) {
if (err) return res.json(500, err);
res.json(results);
});
},
create: function(req, res) {
create: function (req, res) {
log.info("users.create %j", req.body);
var user = new User({
@ -139,7 +138,7 @@ module.exports = function(config, directory) {
deleted: false
});
return user.save(function(err) {
return user.save(function (err) {
if (err)
log.error("Error: %s", err);
@ -147,17 +146,35 @@ module.exports = function(config, directory) {
});
},
update: function(req, res) {
get: function(req, res, next) {
var id = req.param('user_id');
log.info("users.get %s", id);
User.findById(id)
.select('email picture perms groups name')
.exec()
.then((user) => {
if (!user) {
return next(new Error('Failed to load user ' + id));
}
res.json(user);
})
.catch((err) => {
next(err);
});
},
update: function (req, res) {
var id = req.param('user_id');
log.info("users.update %s %j", id, req.body);
return User.findById(id, function(err, user) {
return User.findById(id, function (err, user) {
user.email = req.body.email;
user.name = req.body.name;
user.groups = req.body.groups;
user.perms = req.body.perms;
return user.save(function(err) {
return user.save(function (err) {
if (err)
log.err("Error: %s", err);
@ -166,7 +183,7 @@ module.exports = function(config, directory) {
});
},
clocks: function(req, res) {
clocks: function (req, res) {
var id = req.param('user_id');
var criteria = {
@ -175,7 +192,7 @@ module.exports = function(config, directory) {
var query = Clock.find(criteria)
.sort('-dt')
.exec(function(err, results) {
.exec(function (err, results) {
if (err) {
res.json(500, err);
} else {

View File

@ -11,9 +11,9 @@ var mongoose = require('mongoose'),
Device = mongoose.model('Device'),
User = mongoose.model('User');
module.exports = function(config, calendar) {
module.exports = function (config, calendar) {
return {
index: function(req, res) {
index: function (req, res) {
log.info("workorders.index %j", req.query);
@ -23,12 +23,12 @@ module.exports = function(config, calendar) {
Workorder
.find({
deleted: false,
'scheduling.start': { '$gte': start, '$lt': end }
'scheduling.start': {'$gte': start, '$lt': end}
})
.populate('client', 'name identifier address')
.populate('techs', 'name')
.sort('-scheduling.start client.name')
.exec(function(err, results) {
.exec(function (err, results) {
if (err) {
res.json(500, err);
} else {
@ -37,7 +37,7 @@ module.exports = function(config, calendar) {
});
},
get: function(req, res, next) {
get: function (req, res, next) {
var id = req.param('workorder_id');
log.info("workorders.get %s", id);
@ -46,7 +46,7 @@ module.exports = function(config, calendar) {
.populate('techs', 'name')
.populate('createdBy', 'name')
.populate('modifiedBy', 'name')
.exec(function(err, workorder) {
.exec(function (err, workorder) {
if (err) return next(err);
if (!workorder) return next(new Error('Failed to load workorder ' + id));
@ -54,7 +54,7 @@ module.exports = function(config, calendar) {
});
},
create: function(req, res, next) {
create: function (req, res, next) {
log.info("workoreders.create %j", req.body);
var server = email.server.connect({
@ -79,7 +79,8 @@ module.exports = function(config, calendar) {
techs: req.body.techs,
alternativeContact: req.body.alternativeContact,
trackingNumber: req.body.trackingNumber,
devices: req.body.devices
devices: req.body.devices,
workorderType: req.body.workorderType
});
var notify = req.body._notify || "";
@ -90,41 +91,41 @@ module.exports = function(config, calendar) {
var jsonResult;
async.waterfall([
function(callback) {
function (callback) {
Counter.collection.findAndModify(
{ name: 'workorder' },
{name: 'workorder'},
[],
{ $inc: { seq: 1 } },
{ 'new': true, upsert: true },
function(err, result) {
workorder.biomedId = result.seq - 1;
{$inc: {seq: 1}},
{'new': true, upsert: true},
function (err, result) {
workorder.biomedId = result.value.seq - 1;
callback(err);
});
},
function(callback) {
Client.findById(req.body.client, function(err, result) {
function (callback) {
Client.findById(req.body.client, function (err, result) {
client = result;
callback(err);
});
},
function(callback) {
Device.find({'_id': { $in: req.body.devices }})
function (callback) {
Device.find({'_id': {$in: req.body.devices}})
.populate({path: 'deviceType'})
.exec(function(err, results) {
.exec(function (err, results) {
devices = results;
callback(err);
});
},
function(callback) {
function (callback) {
User.find({
'_id': { $in: workorder.techs }
'_id': {$in: workorder.techs}
},
function(err, result) {
function (err, result) {
techs = result;
callback(err);
});
},
function(callback) {
function (callback) {
calendar.scheduleEvent({
summary: generateSummary(client),
description: generateDescription(client, workorder, req.user, null, null, devices),
@ -132,14 +133,14 @@ module.exports = function(config, calendar) {
start: workorder.scheduling.start,
end: workorder.scheduling.end,
attendees: generateAttendees(techs, workorder)
}, function(err, result) {
}, function (err, result) {
if (result) {
workorder.calendarId = result.id;
}
callback(err);
});
},
function(callback) {
function (callback) {
if (!notify)
return callback(null);
@ -152,7 +153,7 @@ module.exports = function(config, calendar) {
var subject = 'Workorder created: ' + workorder.biomedId;
async.waterfall([
function(cb) {
function (cb) {
if (to && to.length > 0) {
var msg = {
text: description,
@ -160,12 +161,14 @@ module.exports = function(config, calendar) {
to: to,
subject: subject
};
server.send(msg, function(err, message) { cb(err); });
server.send(msg, function (err, message) {
cb(err);
});
} else {
cb();
}
},
function(cb) {
function (cb) {
if (techTo) {
var msg = {
text: techDescription,
@ -173,34 +176,42 @@ module.exports = function(config, calendar) {
to: techTo,
subject: subject
};
server.send(msg, function(err, message) { cb(err); });
server.send(msg, function (err, message) {
cb(err);
});
} else {
cb();
}
}
], callback);
},
function(callback) {
workorder.save(function(err, result) { callback(err, result); });
function (callback) {
workorder.save(function (err, result) {
callback(err, result);
});
},
function(result, callback) {
function (result, callback) {
jsonResult = result;
Client.findByIdAndUpdate(req.body.client, { $push: { 'workorders': result.id } },
function(err, ignored) { callback(err, result) });
Client.findByIdAndUpdate(req.body.client, {$push: {'workorders': result.id}},
function (err, ignored) {
callback(err, result)
});
},
function(result, callback) {
function (result, callback) {
if (workorder.maintenanceType) {
var key = 'pms.' + date.getFullYear() + '-' + date.getMonth() + '.' + workorder.maintenanceType;
var cmd = { $inc: {} };
var cmd = {$inc: {}};
cmd.$inc[key] = 1;
Client.findByIdAndUpdate(req.body.client, cmd, function(err, ignored) { callback(err, result) });
Client.findByIdAndUpdate(req.body.client, cmd, function (err, ignored) {
callback(err, result)
});
} else {
callback(null, result);
}
},
],
function(err, result) {
function (err, result) {
if (!err) {
res.json(jsonResult);
} else {
@ -209,7 +220,7 @@ module.exports = function(config, calendar) {
});
},
update: function(req, res, next) {
update: function (req, res, next) {
var server = email.server.connect({
user: config.email.user,
password: config.email.password,
@ -232,8 +243,8 @@ module.exports = function(config, calendar) {
var notify = req.body._notify || "";
async.waterfall([
function(callback) {
Workorder.findById(id, function(err, result) {
function (callback) {
Workorder.findById(id, function (err, result) {
workorder = result;
workorder.emails = req.body.emails;
@ -245,35 +256,41 @@ module.exports = function(config, calendar) {
workorder.scheduling = req.body.scheduling;
workorder.status = req.body.status;
workorder.techs = req.body.techs
.filter(function(e) { return e; })
.map(function(t) { return t._id; });
.filter(function (e) {
return e;
})
.map(function (t) {
return t._id;
});
workorder.invoiceNumber = req.body.invoiceNumber;
workorder.invoicedTime = req.body.invoicedTime;
workorder.invoicedOn = req.body.invoicedOn;
workorder.checkNumber = req.body.checkNumber;
workorder.paidOn = req.body.paidOn;
workorder.alternativeContact = req.body.alternativeContact;
workorder.trackingNumber = req.body.trackingNumber;
workorder.devices = req.body.devices;
workorder.workorderType = req.body.workorderType;
callback(err);
});
},
function(callback) {
Client.findById(workorder.client, function(err, result) {
function (callback) {
Client.findById(workorder.client, function (err, result) {
client = result;
callback(err);
});
},
function(callback) {
Device.find({'_id': { $in: workorder.devices }})
function (callback) {
Device.find({'_id': {$in: workorder.devices}})
.populate({path: 'deviceType'})
.exec(function(err, results) {
.exec(function (err, results) {
devices = results;
callback(err);
});
},
function(callback) {
function (callback) {
if (workorder.createdBy) {
User.findById(workorder.createdBy, function(err, result) {
User.findById(workorder.createdBy, function (err, result) {
createdBy = result;
callback(err);
});
@ -281,9 +298,9 @@ module.exports = function(config, calendar) {
callback(null);
}
},
function(callback) {
function (callback) {
if (workorder.modifiedBy) {
User.findById(workorder.modifiedBy, function(err, result) {
User.findById(workorder.modifiedBy, function (err, result) {
modifiedBy = result;
callback(err);
});
@ -291,16 +308,16 @@ module.exports = function(config, calendar) {
callback(null);
}
},
function(callback) {
function (callback) {
User.find({
'_id': { $in: workorder.techs }
'_id': {$in: workorder.techs}
},
function(err, result) {
function (err, result) {
techs = result;
callback(err);
});
},
function(callback) {
function (callback) {
calendar.updateEvent({
summary: generateSummary(client),
description: generateDescription(client, workorder, null, null, null, devices),
@ -309,11 +326,11 @@ module.exports = function(config, calendar) {
end: workorder.scheduling.end,
attendees: generateAttendees(techs, workorder),
eventId: workorder.calendarId
}, function(err, result) {
}, function (err, result) {
callback(err);
});
},
function(callback) {
function (callback) {
if (!notify)
return callback(null);
@ -327,7 +344,7 @@ module.exports = function(config, calendar) {
var subject = 'Workorder updated: ' + workorder.biomedId;
async.waterfall([
function(cb) {
function (cb) {
if (to && to.length > 0) {
var msg = {
text: description,
@ -335,12 +352,14 @@ module.exports = function(config, calendar) {
to: to,
subject: subject
};
server.send(msg, function(err, message) { cb(err); });
server.send(msg, function (err, message) {
cb(err);
});
} else {
cb();
}
},
function(cb) {
function (cb) {
if (techTo) {
var msg = {
text: techDescription,
@ -348,20 +367,22 @@ module.exports = function(config, calendar) {
to: techTo,
subject: subject
};
server.send(msg, function(err, message) { cb(err); });
server.send(msg, function (err, message) {
cb(err);
});
} else {
cb();
}
}
], callback);
},
function(callback) {
workorder.save(function(err) {
function (callback) {
workorder.save(function (err) {
callback(err);
})
}
],
function(err) {
function (err) {
if (err)
log.error("Error: %s", err);
@ -369,17 +390,17 @@ module.exports = function(config, calendar) {
});
},
destroy: function(req, res, next) {
destroy: function (req, res, next) {
var id = req.param('workorder_id');
log.info("workorders.destroy %s", id);
return Workorder.findById(id, function(err, workorder) {
return Workorder.findById(id, function (err, workorder) {
workorder.deleted = true;
return workorder.save(function(err) {
return workorder.save(function (err) {
if (!err) {
calendar.deleteEvent(workorder.calendarId, function(err) {
calendar.deleteEvent(workorder.calendarId, function (err) {
return res.json(workorder);
});
} else {
@ -525,7 +546,9 @@ function generateDescription(client, workorder, createdBy, modifiedBy, techs, de
}
function generateAttendees(techs, workorder) {
return techs.map(function(t) { return t.email; }).concat(workorder.emails);
return techs.map(function (t) {
return t.email;
}).concat(workorder.emails);
}
function generateToLine(techs) {

View File

@ -0,0 +1,30 @@
"use strict";
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
const EXCEPTION_REASONS = [
'late_to_first_workorder',
'too_little_travel',
'too_much_travel'
];
var schema = new Schema({
user: {
type: ObjectId,
ref: 'User',
required: true
},
date: {
type: Date,
required: true
},
reason: {
type: String,
enum: EXCEPTION_REASONS,
required: true
}
});
module.exports = mongoose.model('TimeClockException', schema);

View File

@ -1,37 +1,49 @@
"use strict";
var moment = require('moment');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var schema = new Schema({
user: {
type: ObjectId,
ref: 'User'
ref: 'User',
required: true
},
client: {
type: ObjectId,
ref: 'Client'
ref: 'Client',
required: function() {
return this.type === 'workorder';
}
},
workorder: {
type: ObjectId,
ref: 'Workorder'
ref: 'Workorder',
required: function() {
return this.type === 'workorder';
}
},
status: {
type: String,
enum: ['open', 'closed']
enum: ['open', 'closed'],
required: true
},
start: {
type: Date
type: Date,
required: true
},
end: {
type: Date
type: Date,
required: function() {
return this.status === 'closed';
}
},
duration: {
@ -41,18 +53,54 @@ var schema = new Schema({
type: {
type: String,
enum: [ 'workorder', 'workday', 'nonBillable' ]
enum: ['workorder', 'workday', 'nonBillable'],
required: true
},
reason: {
type: String,
enum: ['shop', 'break', 'pto', 'meeting', 'event', 'weather', 'holiday']
enum: ['shop', 'break', 'pto', 'meeting', 'event', 'weather', 'holiday'],
required: function() {
return this.type === 'nonBillable';
}
},
notes: {
type: String,
trim: true
trim: true,
required: function() {
return this.type === 'workorder' && this.status === 'closed';
}
}
});
schema.pre('save', function (next) {
if (this.status === 'open') {
this.end = undefined;
}
if (this.type === 'workorder') {
this.reason = undefined;
}
if (this.type !== 'workorder') {
this.workorder = undefined;
this.client = undefined;
}
if (this.start && this.end) {
this.duration = moment(this.end).diff(this.start, 'seconds');
}
next();
});
schema.pre('validate', function (next) {
if (this.start > this.end) {
return next(new Error('End date must be greater than start date.'));
}
next();
});
module.exports = mongoose.model('TimeClockSpan', schema);

View File

@ -11,10 +11,26 @@ var userSchema = new Schema({
picture: String,
refreshToken: String,
accessToken: String,
groups: [String],
perms: [String],
deleted: { type: Boolean, default: false }
employmentType: {
type: String,
enum: ['hourly', 'salary'],
default: 'hourly',
required: true
},
unpaidTravel: {
type: Number,
default: 0,
required: true
},
deleted: {
type: Boolean,
default: false
}
});
userSchema.methods.hasPermission = function(perm) {

View File

@ -1,14 +1,14 @@
var mongoose = require('mongoose')
Schema = mongoose.Schema,
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var workorderSchema = new Schema({
biomedId: Number,
client: { type: ObjectId, ref: 'Client' },
client: {type: ObjectId, ref: 'Client'},
emails: [String],
createdOn: Date,
createdBy: { type: ObjectId, ref: 'User' },
modifiedBy: { type: ObjectId, ref: 'User' },
createdBy: {type: ObjectId, ref: 'User'},
modifiedBy: {type: ObjectId, ref: 'User'},
reason: String,
maintenanceType: String,
remarks: String,
@ -18,20 +18,53 @@ var workorderSchema = new Schema({
end: Date
},
calendarId: String,
techs: [{ type: ObjectId, ref: 'User' }],
techs: [{type: ObjectId, ref: 'User'}],
history: [{
oldValues: {},
newValues: {},
modifiedBy: { type: ObjectId, ref: 'User' }
modifiedBy: {type: ObjectId, ref: 'User'}
}],
deleted: { type: Boolean, default: false },
deleted: {type: Boolean, default: false},
invoiceNumber: String,
invoicedTime: String,
invoicedOn: Date,
checkNumber: String,
paidOn: Date,
alternativeContact: String,
trackingNumber: String,
devices: [{ type: ObjectId, ref: 'Device' }]
devices: [{type: ObjectId, ref: 'Device'}],
workorderType: {
type: String,
enum: [
'office',
'anesthesia',
'biomed',
'bsp',
'ice',
'imaging',
'sales',
'sterile-processing',
'depot',
'trace-gas',
'room-air-exchange',
'isolation-panels',
'ups-systems',
'relocation',
'ice-maker',
'waste-management-system',
'medgas',
'staffing',
'ert',
'shop',
'break',
'pto',
'meeting',
'event',
'weather',
'legacy'
],
default: 'legacy'
},
});
module.exports = mongoose.model('Workorder', workorderSchema);

60
app/routes/exceptions.js Normal file
View File

@ -0,0 +1,60 @@
"use strict";
const moment = require('moment-timezone');
const _ = require('lodash');
/**
* GET /api/exceptions
*/
function index(req, res) {
req.check('user').isMongoId();
req.check('date').optional().isISO8601();
req.check('week').optional().isISO8601();
if (!req.query.date && !req.query.week) {
return res.json({
error: {
message: 'Must specify a date filter.'
}
});
}
const query = {
user: req.query.user
};
if (req.query.date) {
const date = moment(req.query.date);
const startOfDay = date.clone().startOf('day');
const endOfDay = date.clone().endOf('day');
query.date = {
$gte: startOfDay,
$lte: endOfDay
};
}
if (req.query.week) {
const week = moment(req.query.week);
const startOfWeek = week.clone().startOf('week');
const endOfWeek = week.clone().endOf('week');
query.date = {
$gte: startOfWeek,
$lte: endOfWeek
};
}
var results = req.db.TimeClockException
.find(query)
.sort('date')
.exec();
res.promise(results);
}
module.exports = {
index
};

9
app/routes/index.js Normal file
View File

@ -0,0 +1,9 @@
'use strict';
module.exports = {
exceptions: require('./exceptions'),
misc: require('./misc'),
spans: require('./spans'),
users: require('./users'),
workorders: require('./workorders')
};

53
app/routes/misc.js Normal file
View File

@ -0,0 +1,53 @@
"use strict";
const email = require('../util/email');
const moment = require('moment-timezone');
const _ = require('lodash');
var config = require('../../config/config')['prod'];
var partsRequestTemplate = email.template(
'partsRequest.html.tmpl',
'partsRequest.text.tmpl',
'Parts Request',
[
'techName',
'requestDate',
'customerId',
'customerName',
'customerContact',
'customerPhone',
'biomedId',
'manufacture',
'model',
'serialNumber',
'vendor',
'vendorPhone',
'partNumber',
'description',
'specialNotes'
]
);
/**
* POST /api/misc/partsRequest
*/
function partsRequest(req, res) {
const message = {
to: config.email.partsRequest
};
const defaultValues = {
techName: `${req.user.name.first} ${req.user.name.last}`,
requestDate: moment().format('LLLL')
};
const values = _.assign({}, req.body, defaultValues);
res.promise(email.send(message, partsRequestTemplate, values));
}
module.exports = {
partsRequest
};

97
app/routes/spans.js Normal file
View File

@ -0,0 +1,97 @@
"use strict";
const moment = require('moment-timezone');
const _ = require('lodash');
/**
* GET /api/spans
*/
function index(req, res) {
req.check('user').optional().isMongoId();
req.check('workorder').optional().isMongoId();
req.check('date').optional().isISO8601();
req.check('week').optional().isISO8601();
if (!req.query.user && !req.query.workorder) {
return res.json({
error: {
message: 'Must specify a type filter.'
}
});
}
if (req.query.user && !req.query.date && !req.query.week) {
return res.json({
error: {
message: 'Must specify a date filter.'
}
});
}
const query = {};
if (req.query.user) {
query.user = req.query.user;
}
if (req.query.workorder) {
query.workorder = req.query.workorder;
}
if (req.query.date) {
const date = moment(req.query.date);
const startOfDay = date.clone().startOf('day');
const endOfDay = date.clone().endOf('day');
query.start = {
$gte: startOfDay,
$lte: endOfDay
};
}
if (req.query.week) {
const week = moment(req.query.week);
const startOfWeek = week.clone().startOf('week');
const endOfWeek = week.clone().endOf('week');
query.start = {
$gte: startOfWeek,
$lte: endOfWeek
};
}
var results = req.db.TimeClockSpan
.find(query)
.sort('start')
.exec();
res.promise(results);
}
/**
* POST /api/spans/:user_id
*/
function update(req, res) {
req.check('id').isMongoId();
var data = req.body;
delete data._id;
delete data.__v;
const result = req.db.TimeClockSpan
.findById(req.params.id)
.exec()
.then((entity) => {
_.assign(entity, data);
return entity.save();
});
res.promise(result);
}
module.exports = {
index,
update
};

184
app/routes/users.js Normal file
View File

@ -0,0 +1,184 @@
"use strict";
const Promise = require('bluebird');
const moment = require('moment-timezone');
const _ = require('lodash');
function filterFields(user) {
const obj = user.toObject();
delete obj.accessToken;
delete obj.refreshToken;
return obj
}
/**
* GET /api/users/:id
*/
function fetch(req, res) {
let result;
if (req.params.id === 'me') {
result = Promise.resolve(req.user);
} else {
result = req.db.User.findById(req.params.id);
}
res.promise(result.then(filterFields));
}
/**
* POST /api/users/:id
*/
function update(req, res) {
req.check('id').isMongoId();
var data = req.body;
delete data._id;
delete data.__v;
delete data.name;
delete data.email;
delete data.accessToken;
delete data.refreshToken;
delete data.deleted;
const result = req.db.User
.findById(req.params.id)
.exec()
.then((entity) => {
_.assign(entity, data);
return entity.save();
})
.then(filterFields);
res.promise(result);
}
/**
* GET /api/users/:id/daysWorked
*/
function daysWorked(req, res) {
const id = req.params.id === 'me' ? req.user.id : req.params.id;
const query = {
user: id,
type: 'workday'
};
const result = req.db.TimeClockSpan
.find(query)
.exec()
.then((records) => _.chain(records).reduce(accumulateDaysWorked, []).values());
res.promise(result);
}
/**
* GET /api/users/:id/weeksWorked
*/
function weeksWorked(req, res) {
const id = req.params.id === 'me' ? req.user.id : req.params.id;
const query = {
user: id,
type: 'workday'
};
const result = req.db.TimeClockSpan
.find(query)
.exec()
.then((records) => _.chain(records).reduce(accumulateWeeksWorked, []).values());
res.promise(result);
}
/**
* GET /api/users/:id/timeClock
*/
function timeClock(req, res) {
const id = req.params.id === 'me' ? req.user.id : req.params.id;
const date = moment(req.query.date);
const startOfDay = date.clone().startOf('day');
const endOfDay = date.clone().endOf('day');
var spans = req.db.TimeClockSpan
.find({
user: id,
start: {
$gte: startOfDay,
$lte: endOfDay
}
})
.sort({ start: 1 })
.exec();
var exceptions = req.db.TimeClockException
.find({
user: id,
date: {
$gte: startOfDay,
$lte: endOfDay
}
})
.exec();
var workorders = spans
.then(extractIds('workorder'))
.then((ids) => {
return req.db.Workorder
.find({
_id: {
$in: ids
}
})
.populate('client', 'name identifier')
.exec();
})
.then(indexById);
res.promise(Promise.props({
spans,
exceptions,
workorders
}));
}
function accumulateDaysWorked(result, record) {
const date = moment(record.start).local().startOf('day').format('YYYY-MM-DD');
if (result.indexOf(date) === -1) {
result.push(date);
}
return result;
}
function accumulateWeeksWorked(result, record) {
const date = moment(record.start).local().startOf('week').format('YYYY-MM-DD');
if (result.indexOf(date) === -1) {
result.push(date);
}
return result;
}
function extractIds(field) {
return (data) => _(data)
.pluck(field)
.reject(_.isUndefined)
.uniq((id) => id.toString())
.value();
}
function indexById(data) {
return _.indexBy(data, 'id')
}
module.exports = {
fetch,
update,
daysWorked,
weeksWorked,
timeClock
};

67
app/routes/workorders.js Normal file
View File

@ -0,0 +1,67 @@
"use strict";
const Promise = require('bluebird');
const moment = require('moment-timezone');
const _ = require('lodash');
/**
* GET /api/workorders/:id/timeClock
*/
function timeClock(req, res) {
req.check('id').isMongoId();
const id = req.params.id;
const spans = req.db.TimeClockSpan
.find({
workorder: id
})
.exec();
const users = spans
.then(extractIds('user'))
.then((ids) => {
return req.db.User
.find({
_id: {
$in: ids
}
})
.select('name picture')
.exec();
})
.then(indexById);
const duration = spans
.then((spans) => {
let result = 0;
spans.forEach((span) => {
if (span.duration) {
result += span.duration;
}
});
return result;
});
res.promise(Promise.props({
duration,
spans,
users
}));
}
function extractIds(field) {
return (data) => _(data)
.pluck(field)
.reject(_.isUndefined)
.uniq((id) => id.toString())
.value();
}
function indexById(data) {
return _.indexBy(data, 'id')
}
module.exports = {
timeClock
};

View File

@ -0,0 +1,74 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width">
</head>
<body style="background-color:#eee;color:#333;font-family:Helvetica, Arial, sans-serif;line-height:1.25;-webkit-text-size-adjust:100%;">
<table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%">
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="20" cellspacing="0" width="600">
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color:#fff">
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="48" width="100%" style="background-color:#eee;">
<tr>
<td valign="middle">
<h3 style="font-weight: 300">Atlantic Biomedical</h3>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="48" width="100%" style="background-color:#fff;">
<tr>
<td align="center" valign="middle">
<h4 style="font-weight: 300">Tech Exception</h4>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="1" width="100%">
<tr>
<td align="center" valign="middle" style="background-color: #eeeeee" width="199"></td>
<td align="center" valign="middle" style="background-color: #039BE5" width="202"></td>
<td align="center" valign="middle" style="background-color: #eeeeee" width="199"></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="0" width="100%">
<tr>
<td style="padding:24px;">
<table width="100%">
<tr>
<td colspan="2">The following exception was made by <b><%- techName %></b> at <b><%- date %></b></td>
</tr>
<tr>
<td colspan="2"><%- message %></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

View File

@ -0,0 +1,3 @@
The following exception was made by <%- techName %> on <%- date %>
<%- message %>

View File

@ -0,0 +1,146 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width">
</head>
<body style="background-color:#eee;color:#333;font-family:Helvetica, Arial, sans-serif;line-height:1.25;-webkit-text-size-adjust:100%;">
<table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%">
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="20" cellspacing="0" width="600">
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color:#fff">
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="48" width="100%" style="background-color:#eee;">
<tr>
<td valign="middle">
<h3 style="font-weight: 300">Atlantic Biomedical</h3>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="48" width="100%" style="background-color:#fff;">
<tr>
<td align="center" valign="middle">
<h4 style="font-weight: 300">Parts Request</h4>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="1" width="100%">
<tr>
<td align="center" valign="middle" style="background-color: #eeeeee" width="199"></td>
<td align="center" valign="middle" style="background-color: #039BE5" width="202"></td>
<td align="center" valign="middle" style="background-color: #eeeeee" width="199"></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" height="0" width="100%">
<tr>
<td style="padding:24px;">
<table width="100%">
<tr>
<td colspan="2">The following request for parts was made by <b><%- techName %></b> on <b><%- requestDate %></b></td>
</tr>
<tr>
<td colspan="2"><h4>Customer</h4></td>
</tr>
<tr>
<td>ID</td>
<td><%- customerId %></td>
</tr>
<tr>
<td>Name</td>
<td><%- customerName %></td>
</tr>
<% if (customerContact) { %>
<tr>
<td>Contact</td>
<td><%- customerContact %></td>
</tr>
<% } %>
<% if (customerPhone) { %>
<tr>
<td>Phone Number</td>
<td><%- customerPhone %></td>
</tr>
<% } %>
<% if (biomedId) { %>
<tr>
<td>Atlantic Biomedical ID</td>
<td><%- biomedId %></td>
</tr>
<% } %>
<tr style="margin-top: 24px;">
<td colspan="2"><h4>Part Details</h4></td>
</tr>
<tr>
<td>Manufacture</td>
<td><%- manufacture %></td>
</tr>
<tr>
<td>Model</td>
<td><%- model %></td>
</tr>
<tr>
<td>Serial Number</td>
<td><%- serialNumber %></td>
</tr>
<tr>
<td>Vendor</td>
<td><%- vendor %></td>
</tr>
<% if (vendorPhone) { %>
<tr>
<td>Vendor Phone Number</td>
<td><%- vendorPhone %></td>
</tr>
<% } %>
<tr>
<td>Part Number</td>
<td><%- partNumber %></td>
</tr>
<tr>
<td colspan="2"><h4>Other Details</h4></td>
</tr>
<tr>
<td colspan="2">Brief Description</td>
</tr>
<tr>
<td colspan="2"><%- description %></td>
</tr>
<% if (specialNotes) { %>
<tr>
<td colspan="2" style="padding-top: 16px">Special Notes</td>
</tr>
<tr>
<td colspan="2"><%- specialNotes %></td>
</tr>
<% } %>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

View File

@ -0,0 +1,58 @@
The following request for parts was made by <%- techName %> on <%- requestDate %>
Customer
ID:
<%- customerId %>
Name:
<%- customerName %>
<% if (customerContact) { %>
Contact:
<%- customerContact %>
<% } %>
<% if (customerPhone) { %>
Phone Number:
<%- customerPhone %>
<% } %>
<% if (biomedId) { %>
Atlantic Biomedical ID:
<%- biomedId %>
<% } %>
Part Details
Manufacture:
<%- manufacture %>
Model:
<%- model %>
Serial Number:
<%- serialNumber %>
Vendor:
<%- vendor %>
<% if (vendorPhone) { %>
Vendor Phone Number:
<%- vendorPhone %>
<% } %>
Part Number:
<%- partNumber %>
Other Details
Brief Description:
<%- description %>
<% if (specialNotes) { %>
Special Notes:
<%- specialNotes %>
<% } %>

100
app/util/email.js Normal file
View File

@ -0,0 +1,100 @@
'use strict';
const email = require('emailjs');
const _ = require('lodash');
const path = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
var config = require('../../config/config')['prod'];
const DEFAULT_HEADERS = {
from: 'api@atlanticbiomedical.com'
};
function template(htmlFile, textFile, subjectTemplate, defaultValues) {
if (_.isArray(defaultValues)) {
defaultValues = _.reduce(defaultValues, (result, key) => {
result[key] = '';
return result;
}, {});
}
const builder = template => {
template = _.template(template);
return (values) => {
values = _.assign({}, defaultValues, values);
return template(values);
};
};
var htmlTemplate = fs.readFileAsync(path.join(__dirname, '../templates', htmlFile));
var textTemplate = fs.readFileAsync(path.join(__dirname, '../templates', textFile));
return Promise
.props({
html: htmlTemplate,
text: textTemplate,
subject: subjectTemplate
})
.then(templates => {
return {
html: builder(templates.html),
text: builder(templates.text),
subject: builder(templates.subject)
}
});
}
function send(headers, template, values) {
var message = _.assign({}, DEFAULT_HEADERS, headers);
message = prepairHeaders(message);
return template.then(tmpl => {
message.text = tmpl.text(values);
message.subject = tmpl.subject(values);
message.attachment = [
{data: tmpl.html(values), alternative: true}
];
const server = email.server.connect({
user: config.email.user,
password: config.email.password,
host: 'smtp.gmail.com',
ssl: true
});
return Promise.fromCallback(callback => {
server.send(message, callback);
});
})
}
function prepairHeaders(headers) {
return _.reduce(headers, (result, header, key) => {
if (!_.isArray(header)) {
header = [header];
}
if (key === 'subject') {
result[key] = header;
} else {
result[key] = _
.map(header, entry => {
if (_.isPlainObject(entry)) {
return `${entry.name} <${entry.email}>`;
} else {
return `<${entry}>`;
}
})
.join(', ');
}
return result;
}, {});
}
module.exports = {
send,
template
};

View File

@ -8,7 +8,7 @@ var moment = require('moment');
var ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token';
var PEOPLE_API_URL = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';
module.exports = function(app, passport, config) {
module.exports = function (app, passport, config) {
function createJWT(user) {
var payload = {
@ -20,7 +20,7 @@ module.exports = function(app, passport, config) {
return jwt.encode(payload, config.auth.jwtSecret);
}
app.post('/auth2', function(req, res) {
app.post('/auth2', function (req, res) {
var params = {
code: req.body.code,
client_id: req.body.clientId,
@ -29,7 +29,7 @@ module.exports = function(app, passport, config) {
grant_type: 'authorization_code'
};
request.post(ACCESS_TOKEN_URL, { json: true, form: params }, function(err, response, token) {
request.post(ACCESS_TOKEN_URL, {json: true, form: params}, function (err, response, token) {
console.log(token);
var accessToken = token.access_token;
@ -37,19 +37,19 @@ module.exports = function(app, passport, config) {
Authorization: 'Bearer ' + accessToken
};
request.get({ url: PEOPLE_API_URL, headers: headers, json: true }, function(err, response, profile) {
request.get({url: PEOPLE_API_URL, headers: headers, json: true}, function (err, response, profile) {
if (profile.error) {
return res.status(500).send({ message: profile.error.message });
return res.status(500).send({message: profile.error.message});
}
User.findOne({ email: profile.email.toLowerCase() }, function(err, user) {
User.findOne({email: profile.email.toLowerCase()}, function (err, user) {
if (err) {
return res.status(500).send(err);
}
if (!user || !user.hasPermission('system.login')) {
return res.status(403).send({ message: "You are not authorized to access this portal."});
}
// if (!user || !user.hasPermission('system.login')) {
// return res.status(403).send({message: "You are not authorized to access this portal."});
// }
user.accessToken = token.access_token;
@ -66,12 +66,12 @@ module.exports = function(app, passport, config) {
}
if (profile.picture) {
user.picture = profile.picture.replace('sz=50', 'sz=200');
user.picture = profile.picture.replace('?sz=50', '');
}
user.save()
.then(function() {
res.send({ token: createJWT(user) });
.then(function () {
res.send({token: createJWT(user)});
});
});
});
@ -79,8 +79,7 @@ module.exports = function(app, passport, config) {
});
app.get('/auth', function(req, res, next) {
app.get('/auth', function (req, res, next) {
console.dir(req.headers);
req.session.redirectUrl = req.headers['referer'];
@ -90,10 +89,11 @@ module.exports = function(app, passport, config) {
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/calendar'
]})(req, res, next);
]
})(req, res, next);
});
app.get('/auth/callback', function(req, res, next) {
app.get('/auth/callback', function (req, res, next) {
var callbackHost = req.headers['x-forwarded-host'];
if (!callbackHost) {
@ -103,16 +103,20 @@ module.exports = function(app, passport, config) {
var options = {
callbackURL: 'http://' + callbackHost + '/auth/callback'
};
passport.authenticate('google', options, function(err, user, info) {
passport.authenticate('google', options, function (err, user, info) {
var redirectUrl = '/';
if (err) { return next(err); }
if (!user) { return res.redirect('/login/error'); }
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login/error');
}
log.setPrefix("[%d] %l ");
log.info("User Logged In: %s %s", user.name.first, user.name.last);
res.cookie('atlbid', JSON.stringify(user._id), {signed:true});
res.cookie('atlbid', JSON.stringify(user._id), {signed: true});
if (req.session.redirectUrl) {
redirectUrl = req.session.redirectUrl;
@ -123,8 +127,10 @@ module.exports = function(app, passport, config) {
redirectUrl = '/';
}
req.logIn(user, function(err) {
if (err) { return next(err); }
req.logIn(user, function (err) {
if (err) {
return next(err);
}
});
res.redirect(redirectUrl);
@ -132,13 +138,13 @@ module.exports = function(app, passport, config) {
});
function createAuthenticator(error) {
return function(req, res, next) {
var onError = function() {
return function (req, res, next) {
var onError = function () {
error(req, res, next);
};
var onSuccess = function(user) {
log.setPrefix(function(level) {
var onSuccess = function (user) {
log.setPrefix(function (level) {
return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + user.name.first + ' ' + user.name.last + ' | ';
});
next();
@ -157,15 +163,20 @@ module.exports = function(app, passport, config) {
return onError();
}
console.log(payload);
if (payload.exp <= moment().unix()) {
return onError();
}
User.findById(payload.sub, function(err, user) {
User.findById(payload.sub, function (err, user) {
if (user) {
console.log('Loaded User');
req.user = user;
onSuccess(user);
} else {
onError();
}
});
} else {
onSuccess(req.user);
@ -174,16 +185,16 @@ module.exports = function(app, passport, config) {
}
return {
requiresUiLogin: createAuthenticator(function(req, res, next) {
requiresUiLogin: createAuthenticator(function (req, res, next) {
res.redirect('/login');
}),
requiresApiAccess: createAuthenticator(function(req, res, next) {
requiresApiAccess: createAuthenticator(function (req, res, next) {
res.send(403);
})
};
/*
/*
return {
requiresUiLogin: function(req, res, next) {
if (!req.isAuthenticated()) {
@ -206,5 +217,5 @@ module.exports = function(app, passport, config) {
next();
}
};
*/
*/
};

View File

@ -1,44 +1,22 @@
module.exports = {
development: {
root: require('path').normalize(__dirname + '/..'),
debug: true,
database: 'mongodb://wootbox.wootroot.me/biomed_prod',
auth: {
clientId: '223145213165.apps.googleusercontent.com',
clientSecret: '8MRNar9E_pRTOGTQonPzYOW_',
callback: 'http://devel.portal.atlanticbiomedical.com/auth/callback',
accessToken: 'ya29.AHES6ZR-vUVEh7CZzsEeGFSHqFfXtU1-LHyEAidi0CKhDGQ',
refreshToken: '1/exRXjTaGNlWEo-HZZWyn4NTwJ4TY3wKb-_npce21c50'
},
email: {
user: 'api@atlanticbiomedical.com',
password: 'success4'
},
mysql: {
host: 'biomed.akira.gs',
user: 'biomed_prod',
password: 'wUw3RB8rrXX4HwKj',
database: 'biomed_prod'
}
},
prod: {
root: require('path').normalize(__dirname + '/..'),
debug: true,
database: 'mongodb://localhost/biomed_prod',
database: 'mongodb://localhost/biomed',
auth: {
clientId: '333768673996-8epedo3je5h59n4l97v4dv8nofs7qnee.apps.googleusercontent.com',
clientSecret: 'afu9KhKxckWJ3Tk6uxzp9Pg6',
callback: 'http://localhost:9000/auth/callback',
// accessToken: 'ya29.AHES6ZT1Sj1vpgidR2I_ksLdlV_VeZUjkitnZ01cP6VRrknjUEVbuw',
// refreshToken: '1/XQW9P9FNYm6jikTsV8HOIuPAo1APYhwTH5CLhq9263g'
accessToken: 'ya29.1.AADtN_Xjt0PK6YVs8q5csiQFXQg2ZDtrVhsH6P4a5zm0mHqhGx0Nnjx4Jk68Gw',
refreshToken: '1/_5SkDLYmsi4XNaQyAzld-W5-GEqEqt5byH6VkI-j5QI',
jwtSecret: '97v4dvcsiQFXQg28nofedo3jemsi4XNaQy5h59n4l97m0mHqhGx0Nnjxv4dv8n'
},
email: {
user: 'api@atlanticbiomedical.com',
password: 'success4'
password: 'success4',
partsRequest: 'akirayasha@gmail.com',
exception: 'akirayasha@gmail.com'
},
mysql: {
host: 'localhost',

30
config/db.js Normal file
View File

@ -0,0 +1,30 @@
'use strict';
const mongoose = require('mongoose');
const models = [
'CheckList',
'Client',
'Counter',
'Device',
'DeviceType',
'Pm',
'Post',
'Tag',
'TestRun',
'TimeClockException',
'TimeClockSpan',
'User',
'Workorder'
];
module.exports = function() {
return function(req, res, next) {
req.db = {};
models.forEach((model) => {
req.db[model] = mongoose.model(model);
});
next();
}
};

View File

@ -1,6 +1,9 @@
var express = require('express');
var cors = require('cors');
var ClusterStore = require('strong-cluster-connect-store')(express.session);
var validators = require('./validators');
var db = require('./db');
var promise = require('./promise');
module.exports = function(app, config, passport, piler) {
app.set('showStackError', true);
@ -16,6 +19,9 @@ module.exports = function(app, config, passport, piler) {
// bodyParser should be above methodOverride
app.use(express.bodyParser());
app.use(validators());
app.use(db());
app.use(promise());
app.use(express.methodOverride());
app.use(express.session({ store: new ClusterStore(), secret: 'atlantic_biomed_server_secret' }));
@ -40,9 +46,4 @@ module.exports = function(app, config, passport, piler) {
// routes should be last
app.use(app.router);
});
// app.configure('development', function() {
// // enable live update in development mode.
// piler.liveUpdate();
// });
}

36
config/promise.js Normal file
View File

@ -0,0 +1,36 @@
'use strict';
const mongoose = require('mongoose');
module.exports = function() {
return function(req, res, next) {
res.promise = (promise) => {
promise
.then((data) => {
res.json({
data
});
})
.catch((error) => {
if (typeof error === 'string') {
return res.json(400, {
error: {
message: error
}
});
}
if (error.name === 'ValidationError') {
return res.json(400, {
error: error
});
}
console.log(error.stack);
res.json(500, 'Internal error');
});
};
next();
};
};

View File

@ -1,6 +1,8 @@
var log = require('log4node');
module.exports = function(app, auth, piler, calendar, directory, config) {
var routes = require('../app/routes');
module.exports = function (app, auth, piler, calendar, directory, config) {
piler.addCssUrl("//fonts.googleapis.com/css?family=Open+Sans:400,300");
piler.addCssFile("/css/biomed.less");
@ -28,9 +30,9 @@ module.exports = function(app, auth, piler, calendar, directory, config) {
piler.addJsFile("/js/filters.js");
piler.addJsFile("/js/services.js");
app.get('/crash', function(req, res) {
app.get('/crash', function (req, res) {
console.log('Commiting Suicide for Science!');
process.nextTick(function() {
process.nextTick(function () {
throw new Error("Ermergerd!");
});
});
@ -98,8 +100,14 @@ module.exports = function(app, auth, piler, calendar, directory, config) {
app.get('/api/timeclock', timeclock.index);
app.post('/api/timeclock/clock_in', timeclock.clockIn);
app.post('/api/timeclock/clock_out', timeclock.clockOut);
app.get('/api/timeclock/users/:user_id', timeclock.spansForUser);
app.get('/api/timeclock/workorder/:id', timeclock.workorderDetails);
var timesheet = require('../app/controllers/timesheet')();
app.get('/api/timesheet/summary', timesheet.summary);
app.get('/api/timesheet/:user_id/daysWorked', timesheet.daysWorked);
app.get('/api/timesheet/:user_id/summary', timesheet.userSummary);
var pms = require('../app/controllers/pms');
app.get('/api/pms', pms.index);
@ -109,6 +117,7 @@ module.exports = function(app, auth, piler, calendar, directory, config) {
var users = require('../app/controllers/users')(config, directory);
app.get('/api/users', users.index);
app.get('/api/users/details', users.details);
app.get('/api/users/:user_id', users.get);
app.post('/api/users', users.create);
app.post('/api/users/:user_id', users.update);
app.get('/api/users/:user_id/clocks', users.clocks);
@ -123,9 +132,6 @@ module.exports = function(app, auth, piler, calendar, directory, config) {
var tags = require('../app/controllers/tags')(piler);
app.post('/api/tags', tags.post);
var clock = require('../app/controllers/clock')(piler);
app.post('/api/clock', clock.post);
var site = require('../app/controllers/site')(piler);
var login = require('../app/controllers/login')(piler);
@ -135,6 +141,28 @@ module.exports = function(app, auth, piler, calendar, directory, config) {
var home = require('../app/controllers/home')(piler);
app.get('/', tags.index, auth.requiresUiLogin, clock.index, site.index, home.index);
app.get('*', tags.index, auth.requiresUiLogin, clock.index, site.index, home.index);
// Exceptions
app.get('/api/v2/exceptions', routes.exceptions.index);
// Spans
app.get('/api/v2/spans', routes.spans.index);
app.post('/api/v2/spans/:id', routes.spans.update);
// Users
app.get('/api/v2/users/:id/daysWorked', routes.users.daysWorked);
app.get('/api/v2/users/:id/weeksWorked', routes.users.weeksWorked);
app.get('/api/v2/users/:id/timeClock', routes.users.timeClock);
app.get('/api/v2/users/:id', routes.users.fetch);
app.post('/api/v2/users/:id', routes.users.update);
// Workorders
app.get('/api/v2/workorders/:id/timeClock', routes.workorders.timeClock);
// Misc
app.post('/api/v2/misc/partsRequest', routes.misc.partsRequest);
app.get('/', tags.index, auth.requiresUiLogin, site.index, home.index);
app.get('*', tags.index, auth.requiresUiLogin, site.index, home.index);
};

25
config/validators.js Normal file
View File

@ -0,0 +1,25 @@
'use strict';
var moment = require('moment');
var expressValidator = require('express-validator');
module.exports = function() {
return expressValidator({
customValidators: {
isWeek
},
customSanitizers: {
toMoment
}
});
};
function isWeek(str) {
let week = moment(str, 'YYYY-MM-DD');
return week.isValid() && week.weekday() === 0;
}
function toMoment(str) {
return moment(str);
}

4
node_modules/bluebird/LICENSE generated vendored
View File

@ -1,13 +1,13 @@
The MIT License (MIT)
Copyright (c) 2014 Petka Antonov
Copyright (c) 2013-2015 Petka Antonov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:</p>
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

644
node_modules/bluebird/README.md generated vendored
View File

@ -5,657 +5,25 @@
[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises)
# Introduction
Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance
Bluebird is a fully featured promise library with focus on innovative features and performance
See the [bluebird website](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions.
# Topics
- [Features](#features)
- [Quick start](#quick-start)
- [API Reference and examples](API.md)
- [Support](#support)
- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them)
- [Questions and issues](#questions-and-issues)
- [Error handling](#error-handling)
- [Development](#development)
- [Testing](#testing)
- [Benchmarking](#benchmarks)
- [Custom builds](#custom-builds)
- [For library authors](#for-library-authors)
- [What is the sync build?](#what-is-the-sync-build)
- [License](#license)
- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
- [Changelog](changelog.md)
- [Optimization guide](#optimization-guide)
# Features
<img src="http://petkaantonov.github.io/bluebird/logo.png" alt="bluebird logo" align="right" />
- [Promises A+](http://promisesaplus.com)
- [Synchronous inspection](API.md#synchronous-inspection)
- [Concurrency coordination](API.md#collections)
- [Promisification on steroids](API.md#promisification)
- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management)
- [Cancellation and timeouts](API.md#cancellation)
- [Parallel for C# `async` and `await`](API.md#generators)
- Mind blowing utilities such as
- [`.bind()`](API.md#binddynamic-thisarg---promise)
- [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise)
- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise)
- [And](API.md#core) [much](API.md#timers) [more](API.md#utility)!
- [Practical debugging solutions and sane defaults](#error-handling)
- [Sick performance](benchmark/)
<hr>
# Quick start
## Node.js
npm install bluebird
Then:
```js
var Promise = require("bluebird");
```
## Browsers
There are many ways to use bluebird in browsers:
- Direct downloads
- Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js)
- Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js)
- You may use browserify on the main export
- You may use the [bower](http://bower.io) package.
When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available.
A [minimal bluebird browser build](#custom-builds) is &asymp;38.92KB minified*, 11.65KB gzipped and has no external dependencies.
*Google Closure Compiler using Simple.
#### Browser support
Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported.
[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov)
**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`.
Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+.
After quick start, see [API Reference and examples](API.md)
<hr>
# Support
- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js)
- IRC: #promises @freenode
- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird)
- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open)
<hr>
# What are promises and why should I use them?
You should use promises to turn this:
```js
fs.readFile("file.json", function(err, val) {
if( err ) {
console.error("unable to read file");
}
else {
try {
val = JSON.parse(val);
console.log(val.success);
}
catch( e ) {
console.error("invalid json in file");
}
}
});
```
Into this:
```js
fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
console.log(val.success);
})
.catch(SyntaxError, function(e) {
console.error("invalid json in file");
})
.catch(function(e) {
console.error("unable to read file")
});
```
*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)*
Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O:
```js
try {
var val = JSON.parse(fs.readFileSync("file.json"));
console.log(val.success);
}
//Syntax actually not supported in JS but drives the point
catch(SyntaxError e) {
console.error("invalid json in file");
}
catch(Error e) {
console.error("unable to read file")
}
```
And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code.
You can also use promises to improve code that was written with callback helpers:
```js
//Copyright Plato http://stackoverflow.com/a/19385911/995876
//CC BY-SA 2.5
mapSeries(URLs, function (URL, done) {
var options = {};
needle.get(URL, options, function (error, response, body) {
if (error) {
return done(error)
}
try {
var ret = JSON.parse(body);
return done(null, ret);
}
catch (e) {
done(e);
}
});
}, function (err, results) {
if (err) {
console.log(err)
} else {
console.log('All Needle requests successful');
// results is a 1 to 1 mapping in order of URLs > needle.body
processAndSaveAllInDB(results, function (err) {
if (err) {
return done(err)
}
console.log('All Needle requests saved');
done(null);
});
}
});
```
Is more pleasing to the eye when done with promises:
```js
Promise.promisifyAll(needle);
var options = {};
var current = Promise.resolve();
Promise.map(URLs, function(URL) {
current = current.then(function () {
return needle.getAsync(URL, options);
});
return current;
}).map(function(responseAndBody){
return JSON.parse(responseAndBody[1]);
}).then(function (results) {
return processAndSaveAllInDB(results);
}).then(function(){
console.log('All Needle requests saved');
}).catch(function (e) {
console.log(e);
});
```
Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators.
More reading:
- [Promise nuggets](https://promise-nuggets.github.io/)
- [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html)
- [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1)
- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
# Questions and issues
If you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
# Error handling
This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled.
There are two common pragmatic attempts at solving the problem that promise libraries do.
The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so:
```js
download().then(...).then(...).done();
```
For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place.
The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice.
Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown.
If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so:
```js
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
```
If you want to also enable long stack traces, call:
```js
Promise.longStackTraces();
```
right after the library is loaded.
In node.js use the environment flag `BLUEBIRD_DEBUG`:
```
BLUEBIRD_DEBUG=1 node server.js
```
to enable long stack traces in all instances of bluebird.
Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them.
Long stack traces are enabled by default in the debug build.
#### Expected and unexpected errors
A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about.
Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however:
```js
try {
//code
}
catch(e) {
if( e instanceof WhatIWantError) {
//handle
}
else {
throw e;
}
}
```
Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise).
For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON:
```js
getJSONFromSomewhere().then(function(jsonString) {
return JSON.parse(jsonString);
}).then(function(object) {
console.log("it was valid json: ", object);
}).catch(SyntaxError, function(e){
console.log("don't be evil");
});
```
Here any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`.
Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors?
Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when
their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped.
Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them:
```js
//Read more about promisification in the API Reference:
//API.md
var fs = Promise.promisifyAll(require("fs"));
fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
console.log("Successful json")
}).catch(SyntaxError, function (e) {
console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
console.error("unable to read file, because: ", e.message);
});
```
The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed.
Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand:
```js
.error(function (e) {
console.error("unable to read file, because: ", e.message);
});
```
See [API documentation for `.error()`](API.md#error-rejectedhandler----promise)
Finally, Bluebird also supports predicate-based filters. If you pass a
predicate function instead of an error type, the predicate will receive
the error as an argument. The return result will be used to determine whether
the error handler should be called.
Predicates should allow for very fine grained control over caught errors:
pattern matching, error typesets with set operations and many other techniques
can be implemented on top of them.
Example of using a predicate-based filter:
```js
var Promise = require("bluebird");
var request = Promise.promisify(require("request"));
function clientError(e) {
return e.code >= 400 && e.code < 500;
}
request("http://www.google.com").then(function(contents){
console.log(contents);
}).catch(clientError, function(e){
//A client error like 400 Bad Request happened
});
```
**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions.
<hr>
#### How do long stack traces differ from e.g. Q?
Bluebird attempts to have more elaborate traces. Consider:
```js
Error.stackTraceLimit = 25;
Q.longStackSupport = true;
Q().then(function outer() {
return Q().then(function inner() {
return Q().then(function evenMoreInner() {
a.b.c.d();
}).catch(function catcher(e){
console.error(e.stack);
});
})
});
```
You will see
ReferenceError: a is not defined
at evenMoreInner (<anonymous>:7:13)
From previous event:
at inner (<anonymous>:6:20)
Compare to:
```js
Error.stackTraceLimit = 25;
Promise.longStackTraces();
Promise.resolve().then(function outer() {
return Promise.resolve().then(function inner() {
return Promise.resolve().then(function evenMoreInner() {
a.b.c.d()
}).catch(function catcher(e){
console.error(e.stack);
});
});
});
```
ReferenceError: a is not defined
at evenMoreInner (<anonymous>:7:13)
From previous event:
at inner (<anonymous>:6:36)
From previous event:
at outer (<anonymous>:5:32)
From previous event:
at <anonymous>:4:21
at Object.InjectedScript._evaluateOn (<anonymous>:572:39)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:531:52)
at Object.InjectedScript.evaluate (<anonymous>:450:21)
A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability).
<hr>
# Development
For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies.
Install [node](http://nodejs.org/) and [npm](https://npmjs.org/)
git clone git@github.com:petkaantonov/bluebird.git
cd bluebird
npm install
## Testing
To run all tests, run
node tools/test
If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+:
node-dev --harmony tools/test
You may specify an individual test file to run with the `--run` script flag:
node tools/test --run=cancel.js
This enables output from the test and may give a better idea where the test is failing. The paramter to `--run` can be any file name located in `test/mocha` folder.
#### Testing in browsers
To run the test in a browser instead of node, pass the flag `--browser` to the test tool
node tools/test --run=cancel.js --browser
This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled.
Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active.
#### Supported options by the test tool
The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`.
- `--run=String`. Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder)
- `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter).
- `--browser` - Whether to compile tests for browsers. Default `false`.
- `--port=Number` - Whe port where local server is hosted when testing in browser. Default `9999`
- `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`.
- `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`.
- `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`.
- `--js-hint` - Whether to run JSHint on source files. Default `true`.
- `--saucelabs` Wheter to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser.Default `false`.
## Benchmarks
To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too).
Node 0.11.2+ is required to run the generator examples.
### 1\. DoxBee sequential
Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections.
Command: `bench doxbee`
### 2\. Made-up parallel
This made-up scenario runs 15 shimmed queries in parallel.
Command: `bench parallel`
## Custom builds
Custom builds for browsers are supported through a command-line utility.
<table>
<caption>The following features can be disabled</caption>
<thead>
<tr>
<th>Feature(s)</th>
<th>Command line identifier</th>
</tr>
</thead>
<tbody>
<tr><td><a href="API.md#any---promise"><code>.any</code></a> and <a href="API.md#promiseanyarraydynamicpromise-values---promise"><code>Promise.any</code></a></td><td><code>any</code></td></tr>
<tr><td><a href="API.md#race---promise"><code>.race</code></a> and <a href="API.md#promiseracearraypromise-promises---promise"><code>Promise.race</code></a></td><td><code>race</code></td></tr>
<tr><td><a href="API.md#callstring-propertyname--dynamic-arg---promise"><code>.call</code></a> and <a href="API.md#getstring-propertyname---promise"><code>.get</code></a></td><td><code>call_get</code></td></tr>
<tr><td><a href="API.md#filterfunction-filterer---promise"><code>.filter</code></a> and <a href="API.md#promisefilterarraydynamicpromise-values-function-filterer---promise"><code>Promise.filter</code></a></td><td><code>filter</code></td></tr>
<tr><td><a href="API.md#mapfunction-mapper---promise"><code>.map</code></a> and <a href="API.md#promisemaparraydynamicpromise-values-function-mapper---promise"><code>Promise.map</code></a></td><td><code>map</code></td></tr>
<tr><td><a href="API.md#reducefunction-reducer--dynamic-initialvalue---promise"><code>.reduce</code></a> and <a href="API.md#promisereducearraydynamicpromise-values-function-reducer--dynamic-initialvalue---promise"><code>Promise.reduce</code></a></td><td><code>reduce</code></td></tr>
<tr><td><a href="API.md#props---promise"><code>.props</code></a> and <a href="API.md#promisepropsobjectpromise-object---promise"><code>Promise.props</code></a></td><td><code>props</code></td></tr>
<tr><td><a href="API.md#settle---promise"><code>.settle</code></a> and <a href="API.md#promisesettlearraydynamicpromise-values---promise"><code>Promise.settle</code></a></td><td><code>settle</code></td></tr>
<tr><td><a href="API.md#someint-count---promise"><code>.some</code></a> and <a href="API.md#promisesomearraydynamicpromise-values-int-count---promise"><code>Promise.some</code></a></td><td><code>some</code></td></tr>
<tr><td><a href="API.md#nodeifyfunction-callback---promise"><code>.nodeify</code></a></td><td><code>nodeify</code></td></tr>
<tr><td><a href="API.md#promisecoroutinegeneratorfunction-generatorfunction---function"><code>Promise.coroutine</code></a> and <a href="API.md#promisespawngeneratorfunction-generatorfunction---promise"><code>Promise.spawn</code></a></td><td><code>generators</code></td></tr>
<tr><td><a href="API.md#progression">Progression</a></td><td><code>progress</code></td></tr>
<tr><td><a href="API.md#promisification">Promisification</a></td><td><code>promisify</code></td></tr>
<tr><td><a href="API.md#cancellation">Cancellation</a></td><td><code>cancel</code></td></tr>
<tr><td><a href="API.md#timers">Timers</a></td><td><code>timers</code></td></tr>
<tr><td><a href="API.md#resource-management">Resource management</a></td><td><code>using</code></td></tr>
</tbody>
</table>
Make sure you have cloned the repo somewhere and did `npm install` successfully.
After that you can run:
node tools/build --features="core"
The above builds the most minimal build you can get. You can add more features separated by spaces from the above list:
node tools/build --features="core filter map reduce"
The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features.
Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build
a full version afterwards (after having taken a copy of the bluebird.js somewhere):
node tools/build --debug --main --zalgo --browser --minify
#### Supported options by the build tool
The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`.
- `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`.
- `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`.
- `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`.
- `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`.
- `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`.
- `--features=String` - See [custom builds](#custom-builds)
<hr>
## For library authors
Building a library that depends on bluebird? You should know about a few features.
If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file
that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains:
```js
//NOTE the function call right after
module.exports = require("bluebird/js/main/promise")();
```
Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic.
You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API.
<hr>
## What is the sync build?
You may now use sync build by:
var Promise = require("bluebird/zalgo");
The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards.
The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility
of stack overflow errors and non-deterministic behavior.
The sync build skips the async call trampoline completely, e.g code like:
async.invoke( this.fn, this, val );
Appears as this in the sync build:
this.fn(val);
This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism.
Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads.
```js
var cache = new Map(); //ES6 Map or DataStructures/Map or whatever...
function getResult(url) {
var resolver = Promise.pending();
if (cache.has(url)) {
resolver.resolve(cache.get(url));
}
else {
http.get(url, function(err, content) {
if (err) resolver.reject(err);
else {
cache.set(url, content);
resolver.resolve(content);
}
});
}
return resolver.promise;
}
//The result of console.log is truly random without async guarantees
function guessWhatItPrints( url ) {
var i = 3;
getResult(url).then(function(){
i = 4;
});
console.log(i);
}
```
# Optimization guide
Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome.
A single cohesive guide compiled from the articles will probably be done eventually.
The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
# License
The MIT License (MIT)
Copyright (c) 2014 Petka Antonov
Copyright (c) 2013-2015 Petka Antonov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

1
node_modules/bluebird/changelog.md generated vendored Normal file
View File

@ -0,0 +1 @@
[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html)

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

55
node_modules/bluebird/js/release/assert.js generated vendored Normal file
View File

@ -0,0 +1,55 @@
"use strict";
module.exports = (function(){
var AssertionError = (function() {
function AssertionError(a) {
this.constructor$(a);
this.message = a;
this.name = "AssertionError";
}
AssertionError.prototype = new Error();
AssertionError.prototype.constructor = AssertionError;
AssertionError.prototype.constructor$ = Error;
return AssertionError;
})();
function getParams(args) {
var params = [];
for (var i = 0; i < args.length; ++i) params.push("arg" + i);
return params;
}
function nativeAssert(callName, args, expect) {
try {
var params = getParams(args);
var constructorArgs = params;
constructorArgs.push("return " +
callName + "("+ params.join(",") + ");");
var fn = Function.apply(null, constructorArgs);
return fn.apply(null, args);
} catch (e) {
if (!(e instanceof SyntaxError)) {
throw e;
} else {
return expect;
}
}
}
return function assert(boolExpr, message) {
if (boolExpr === true) return;
if (typeof boolExpr === "string" &&
boolExpr.charAt(0) === "%") {
var nativeCallName = boolExpr;
var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];};
if (nativeAssert(nativeCallName, args, message) === message) return;
message = (nativeCallName + " !== " + message);
}
var ret = new AssertionError(message);
if (Error.captureStackTrace) {
Error.captureStackTrace(ret, assert);
}
throw ret;
};
})();

157
node_modules/bluebird/js/release/async.js generated vendored Normal file
View File

@ -0,0 +1,157 @@
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule");
var Queue = require("./queue");
var util = require("./util");
function Async() {
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule =
schedule.isStatic ? schedule(this.drainQueues) : schedule;
}
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function(e, isNode) {
if (isNode) {
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e));
process.exit(2);
} else {
this.throwLater(e);
}
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
if (schedule.isStatic) {
schedule = function(fn) { setTimeout(fn, 0); };
}
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
this._normalQueue.unshift(fn, receiver, arg);
this._queueTick();
};
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;

67
node_modules/bluebird/js/release/bind.js generated vendored Normal file
View File

@ -0,0 +1,67 @@
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (((this._bitField & 50397184) === 0)) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};

11
node_modules/bluebird/js/release/bluebird.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = require("./promise")();
bluebird.noConflict = noConflict;
module.exports = bluebird;

123
node_modules/bluebird/js/release/call_get.js generated vendored Normal file
View File

@ -0,0 +1,123 @@
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!false) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
if (!false) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};

125
node_modules/bluebird/js/release/cancel.js generated vendored Normal file
View File

@ -0,0 +1,125 @@
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise.isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent.isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this.isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this.isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};

42
node_modules/bluebird/js/release/catch_filter.js generated vendored Normal file
View File

@ -0,0 +1,42 @@
"use strict";
module.exports = function(NEXT_FILTER) {
var util = require("./util");
var getKeys = require("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function(e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error ||
(item != null && item.prototype instanceof Error)) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};

69
node_modules/bluebird/js/release/context.js generated vendored Normal file
View File

@ -0,0 +1,69 @@
"use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function() {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function() {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};

812
node_modules/bluebird/js/release/debuggability.js generated vendored Normal file
View File

@ -0,0 +1,812 @@
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = require("./errors").Warning;
var util = require("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
(false ||
util.env("BLUEBIRD_DEBUG") ||
util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
(debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
2097152);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 2097152) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
Promise.config = function(opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
config.warnings = !!opts.warnings;
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
};
Promise.prototype._execute = function(executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function(onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " +
util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this.isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise) {
if (returnValue === undefined &&
promiseCreated !== null &&
config.longStackTraces &&
config.warnings) {
var msg = "a promise was created in a " + name +
" handler but was not returned from it";
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
formatAndLogError(warning, "", true);
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line ||
stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0) {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent(name, reason, promise);
} catch (e) {
globalEventFired = true;
async.throwLater(e);
}
var domEventFired = false;
if (fireDomEvent) {
try {
domEventFired = fireDomEvent(name.toLowerCase(), {
reason: reason,
promise: promise
});
} catch (e) {
domEventFired = true;
async.throwLater(e);
}
}
if (!globalEventFired && !localEventFired && !domEventFired &&
name === "unhandledRejection") {
formatAndLogError(reason, "Unhandled rejection ");
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj && typeof obj.toString === "function"
? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit -= 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
var fireDomEvent;
var fireGlobalEvent = (function() {
if (util.isNode) {
return function(name, reason, promise) {
if (name === "rejectionHandled") {
return process.emit(name, promise);
} else {
return process.emit(name, reason, promise);
}
};
} else {
var customEventWorks = false;
var anyEventWorks = true;
try {
var ev = new self.CustomEvent("test");
customEventWorks = ev instanceof CustomEvent;
} catch (e) {}
if (!customEventWorks) {
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
self.dispatchEvent(event);
} catch (e) {
anyEventWorks = false;
}
}
if (anyEventWorks) {
fireDomEvent = function(type, detail) {
var event;
if (customEventWorks) {
event = new self.CustomEvent(type, {
detail: detail,
bubbles: false,
cancelable: true
});
} else if (self.dispatchEvent) {
event = document.createEvent("CustomEvent");
event.initCustomEvent(type, false, true, detail);
}
return event ? !self.dispatchEvent(event) : false;
};
}
var toWindowMethodNameMap = {};
toWindowMethodNameMap["unhandledRejection"] = ("on" +
"unhandledRejection").toLowerCase();
toWindowMethodNameMap["rejectionHandled"] = ("on" +
"rejectionHandled").toLowerCase();
return function(name, reason, promise) {
var methodName = toWindowMethodNameMap[name];
var method = self[methodName];
if (!method) return false;
if (name === "rejectionHandled") {
method.call(self, promise);
} else {
method.call(self, reason, promise);
}
return true;
};
}
})();
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
printWarning = function(message, isSoft) {
var color = isSoft ? "\u001b[33m" : "\u001b[31m";
console.warn(color + message + "\u001b[0m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
printWarning = function(message, isSoft) {
console.warn("%c" + message,
isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace
};
};

46
node_modules/bluebird/js/release/direct_resolve.js generated vendored Normal file
View File

@ -0,0 +1,46 @@
"use strict";
module.exports = function(Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
};
};

29
node_modules/bluebird/js/release/each.js generated vendored Normal file
View File

@ -0,0 +1,29 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return this.mapSeries(fn)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseMapSeries(promises, fn)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};

111
node_modules/bluebird/js/release/errors.js generated vendored Normal file
View File

@ -0,0 +1,111 @@
"use strict";
var es5 = require("./es5");
var Objectfreeze = es5.freeze;
var util = require("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};

100
node_modules/bluebird/js/release/finally.js generated vendored Normal file
View File

@ -0,0 +1,100 @@
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.type === 0
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise.isCancelled()) {
var reason =
new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(
new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(
succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success, fail, undefined, {
promise: this,
handler: handler,
called: false,
cancelPromise: null,
type: type
}, undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
return finallyHandler;
};

204
node_modules/bluebird/js/release/generators.js generated vendored Normal file
View File

@ -0,0 +1,204 @@
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise,
Proxyable,
debug) {
var errors = require("./errors");
var TypeError = errors.TypeError;
var util = require("./util");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
promise._setOnCancel(this);
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
this._yieldedPromise = null;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
return this.promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
this._promise = this._generator = null;
};
PromiseSpawn.prototype._promiseCancelled = function() {
if (this._isResolved()) return;
var implementsReturn = typeof this._generator["return"] !== "undefined";
var result;
if (!implementsReturn) {
var reason = new Promise.CancellationError(
"generator .return() sentinel");
Promise.coroutine.returnSentinel = reason;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
result = tryCatch(this._generator["throw"]).call(this._generator,
reason);
this._promise._popContext();
if (result === errorObj && result.e === reason) {
result = null;
}
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator,
undefined);
this._promise._popContext();
}
var promise = this._promise;
this._cleanup();
if (result === errorObj) {
promise._rejectCallback(result.e, false);
} else {
promise.cancel();
}
};
PromiseSpawn.prototype._promiseFulfilled = function(value) {
this._yieldedPromise = null;
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function(reason) {
this._yieldedPromise = null;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function() {
if (this._yieldedPromise instanceof Promise) {
var promise = this._yieldedPromise;
this._yieldedPromise = null;
promise.cancel();
}
};
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
var promise = this._promise;
if (result === errorObj) {
this._cleanup();
return promise._rejectCallback(result.e, false);
}
var value = result.value;
if (result.done === true) {
this._cleanup();
return promise._resolveCallback(value);
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if (((bitField & 33554432) !== 0)) {
this._promiseFulfilled(maybePromise._value());
} else if (((bitField & 16777216) !== 0)) {
this._promiseRejected(maybePromise._reason());
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};

149
node_modules/bluebird/js/release/join.js generated vendored Normal file
View File

@ -0,0 +1,149 @@
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!false) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i+1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode= "var promise;\n" + props.map(function(prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.now = 0; \n\
} \n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
promise._pushContext(); \n\
var callback = this.fn; \n\
var ret = tryCatch(callback)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", code)
(tryCatch, errorObj, Promise);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!false) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};

151
node_modules/bluebird/js/release/map.js generated vendored Normal file
View File

@ -0,0 +1,151 @@
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var EMPTY_ARRAY = [];
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
this._init$(undefined, -2);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = typeof options === "object" && options !== null
? options.concurrency
: 0;
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};

55
node_modules/bluebird/js/release/method.js generated vendored Normal file
View File

@ -0,0 +1,55 @@
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};

51
node_modules/bluebird/js/release/nodeback.js generated vendored Normal file
View File

@ -0,0 +1,51 @@
"use strict";
var util = require("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = require("./errors");
var OperationalError = errors.OperationalError;
var es5 = require("./es5");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;

58
node_modules/bluebird/js/release/nodeify.js generated vendored Normal file
View File

@ -0,0 +1,58 @@
"use strict";
module.exports = function(Promise) {
var util = require("./util");
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var newReason = new Error(reason + "");
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};

755
node_modules/bluebird/js/release/promise.js generated vendored Normal file
View File

@ -0,0 +1,755 @@
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = require("./es5");
var Async = require("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = require("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
var PromiseArray =
require("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = require("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var finallyHandler = require("./finally")(Promise, tryConvertToPromise);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
}
function Promise(executor) {
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._promiseCreated();
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
var prev = async._schedule;
async._schedule = fn;
return prev;
};
Promise.prototype._then = function (
didFulfill,
didReject,
_, receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" && domain.bind(handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
this._bitField = this._bitField | 65536;
};
Promise.prototype._setAsyncGuaranteed = function() {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : domain.bind(reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : domain.bind(reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj || x === promise) {
var err = x === promise ? makeSelfResolutionError() : x.e;
promise._rejectCallback(err, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (handler === finallyHandler) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function(ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
debug);
require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise);
require("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug);
Promise.Promise = Promise;
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./nodeify.js')(Promise);
require('./call_get.js')(Promise);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection);
require('./promisify.js')(Promise, INTERNAL);
require('./any.js')(Promise);
require('./each.js')(Promise, INTERNAL);
require('./filter.js')(Promise, INTERNAL);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};

184
node_modules/bluebird/js/release/promise_array.js generated vendored Normal file
View File

@ -0,0 +1,184 @@
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
var util = require("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if (((bitField & 50397184) === 0)) {
this._promise._setAsyncGuaranteed();
return values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
} else if (((bitField & 33554432) !== 0)) {
values = values._value();
} else if (((bitField & 16777216) !== 0)) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection(
"expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if (((bitField & 50397184) === 0)) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if (((bitField & 33554432) !== 0)) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if (((bitField & 16777216) !== 0)) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
if (this._isResolved() || !this._promise.isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function() {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function() {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};

314
node_modules/bluebird/js/release/promisify.js generated vendored Normal file
View File

@ -0,0 +1,314 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = require("./util");
var nodebackForPromise = require("./nodeback");
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = require("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!false) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn, _, multiArgs) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
var body = "'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode);
body = body.replace("Parameters", parameterDeclaration(newParameterCount));
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL",
body)(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise, multiArgs);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
if (promisifier === makeNodePromisified) {
obj[promisifiedKey] =
makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
} else {
var promisified = promisifier(fn, function() {
return makeNodePromisified(key, THIS, key,
fn, suffix, multiArgs);
});
util.notEnumerableProp(promisified, "__isPromisified__", true);
obj[promisifiedKey] = promisified;
}
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver, multiArgs) {
return makeNodePromisified(callback, receiver, undefined,
callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier,
multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};

118
node_modules/bluebird/js/release/props.js generated vendored Normal file
View File

@ -0,0 +1,118 @@
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = require("./util");
var isObject = util.isObject;
var es5 = require("./es5");
var Es6Map;
if (typeof Map === "function") Es6Map = Map;
var mapToEntries = (function() {
var index = 0;
var size = 0;
function extractEntry(value, key) {
this[index] = value;
this[index + size] = key;
index++;
}
return function mapToEntries(map) {
size = map.size;
index = 0;
var ret = new Array(map.size * 2);
map.forEach(extractEntry, ret);
return ret;
};
})();
var entriesToMap = function(entries) {
var ret = new Es6Map();
var length = entries.length / 2 | 0;
for (var i = 0; i < length; ++i) {
var key = entries[length + i];
var value = entries[i];
ret.set(key, value);
}
return ret;
};
function PropertiesPromiseArray(obj) {
var isMap = false;
var entries;
if (Es6Map !== undefined && obj instanceof Es6Map) {
entries = mapToEntries(obj);
isMap = true;
} else {
var keys = es5.keys(obj);
var len = keys.length;
entries = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
entries[i] = obj[key];
entries[i + len] = key;
}
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val;
if (this._isMap) {
val = entriesToMap(this._values);
} else {
val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
}
this._resolve(val);
return true;
}
return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 2);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};

49
node_modules/bluebird/js/release/race.js generated vendored Normal file
View File

@ -0,0 +1,49 @@
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = require("./util");
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null)
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};

162
node_modules/bluebird/js/release/reduce.js generated vendored Normal file
View File

@ -0,0 +1,162 @@
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
this.constructor$(promises);
var domain = getDomain();
this._fn = domain === null ? fn : domain.bind(fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
this._eachValues = _each === INTERNAL ? [] : undefined;
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
if (this._eachValues !== undefined && accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
this._eachValues.push(value);
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
this._resolve(this._eachValues !== undefined ? this._eachValues
: this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value
._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(),
this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
promise
);
return ret;
}
};

35
node_modules/bluebird/js/release/schedule.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
"use strict";
var util = require("./util");
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
window.navigator.standalone)) {
schedule = function(fn) {
var div = document.createElement("div");
var observer = new MutationObserver(fn);
observer.observe(div, {attributes: true});
return function() { div.classList.toggle("foo"); };
};
schedule.isStatic = true;
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;

43
node_modules/bluebird/js/release/settle.js generated vendored Normal file
View File

@ -0,0 +1,43 @@
"use strict";
module.exports =
function(Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = require("./util");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 33554432;
ret._settledValueField = value;
return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 16777216;
ret._settledValueField = reason;
return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return Promise.settle(this);
};
};

148
node_modules/bluebird/js/release/some.js generated vendored Normal file
View File

@ -0,0 +1,148 @@
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = require("./util");
var RangeError = require("./errors").RangeError;
var AggregateError = require("./errors").AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function() {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};

View File

@ -0,0 +1,96 @@
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled =
Promise.prototype._isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype.isCancelled = function() {
return this._target()._isCancelled();
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};

82
node_modules/bluebird/js/release/thenables.js generated vendored Normal file
View File

@ -0,0 +1,82 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};

66
node_modules/bluebird/js/release/timers.js generated vendored Normal file
View File

@ -0,0 +1,66 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
var afterTimeout = function (promise, message, parent) {
if (!promise.isPending()) return;
var err;
if (typeof message !== "string") {
if (message instanceof Error) {
err = message;
} else {
err = new TimeoutError("operation timed out");
}
} else {
err = new TimeoutError(message);
}
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._reject(err);
parent.cancel();
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
var ret;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
} else {
ret = new Promise(INTERNAL);
setTimeout(function() { ret._fulfill(); }, +ms);
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
function successClear(value) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
return value;
}
function failureClear(reason) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var parent = this.then();
var ret = parent.then();
var handle = setTimeout(function timeoutTimeout() {
afterTimeout(ret, message, parent);
}, ms);
return ret._then(successClear, failureClear, undefined, handle, undefined);
};
};

225
node_modules/bluebird/js/release/using.js generated vendored Normal file
View File

@ -0,0 +1,225 @@
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext, INTERNAL, debug) {
var util = require("./util");
var TypeError = require("./errors").TypeError;
var inherits = require("./util").inherits;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = new Promise(INTERNAL);
function iterator() {
if (i >= len) return ret._fulfill();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret;
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return null;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== null
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
function ResourceList(length) {
this.length = length;
this.promise = null;
this[length-1] = null;
}
ResourceList.prototype._resultCancelled = function() {
var len = this.length;
for (var i = 0; i < len; ++i) {
var item = this[i];
if (item instanceof Promise) {
item.cancel();
}
}
};
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources)
.then(function(inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs
? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function() {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 131072) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~131072);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};

344
node_modules/bluebird/js/release/util.js generated vendored Normal file
View File

@ -0,0 +1,344 @@
"use strict";
var es5 = require("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" ||
typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function(v) {
return Array.from(v);
} : function(v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!((itResult = it.next()).done)) {
ret.push(itResult.value);
}
return ret;
};
asArray = function(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]";
function env(key, def) {
return isNode ? process.env[key] : def;
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
env: env
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;

135
node_modules/bluebird/package.json generated vendored

File diff suppressed because one or more lines are too long

6
node_modules/colors/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,6 @@
language: node_js
node_js:
- "0.11"
- "0.10"
- "0.8"
- "0.6"

23
node_modules/colors/MIT-LICENSE.txt generated vendored Normal file
View File

@ -0,0 +1,23 @@
Original Library
- Copyright (c) Marak Squires
Additional Functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

167
node_modules/colors/ReadMe.md generated vendored Normal file
View File

@ -0,0 +1,167 @@
# colors.js
## get color and style in your node.js console
<img src="https://github.com/Marak/colors.js/raw/master/screenshots/colors.png"/>
## Installation
npm install colors
## colors and styles!
### text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
- grey
### background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
### styles
- reset
- bold
- dim
- italic
- underline
- inverse
- hidden
- strikethrough
### extras
- rainbow
- zebra
- america
- trap
- random
## Usage
By popular demand, `colors` now ships with two types of usages!
The super nifty way
```js
var colors = require('colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red) // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow
console.log('Run the trap'.trap); // Drops the bass
```
or a slightly less nifty way which doesn't extend `String.prototype`
```js
var colors = require('colors/safe');
console.log(colors.green('hello')); // outputs green text
console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text
console.log(colors.inverse('inverse the color')); // inverses the color
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
console.log(colors.trap('Run the trap')); // Drops the bass
```
I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way.
If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object.
## Disabling Colors
To disable colors you can pass the following arguments in the command line to your application:
```bash
node myapp.js --no-color
```
## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data)
```js
var name = 'Marak';
console.log(colors.green('Hello %s'), name);
// outputs -> 'Hello Marak'
```
## Custom themes
### Using standard API
```js
var colors = require('colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
```
### Using string safe API
```js
var colors = require('colors/safe');
// set single property
var error = colors.red;
error('this is red');
// set theme
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
```
*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*

74
node_modules/colors/examples/normal-usage.js generated vendored Normal file
View File

@ -0,0 +1,74 @@
var colors = require('../lib/index');
console.log("First some yellow text".yellow);
console.log("Underline that text".yellow.underline);
console.log("Make it bold and red".red.bold);
console.log(("Double Raindows All Day Long").rainbow)
console.log("Drop the bass".trap)
console.log("DROP THE RAINBOW BASS".trap.rainbow)
console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported
console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + ' styles! '.yellow.bold); // styles not widely supported
console.log("Zebras are so fun!".zebra);
//
// Remark: .strikethrough may not work with Mac OS Terminal App
//
console.log("This is " + "not".strikethrough + " fun.");
console.log('Background color attack!'.black.bgWhite)
console.log('Use random styles on everything!'.random)
console.log('America, Heck Yeah!'.america)
console.log('Setting themes is useful')
//
// Custom themes
//
console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
// outputs grey text
console.log("this is an input".input);
console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(__dirname + '/../themes/generic-logging.js');
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
// outputs grey text
console.log("this is an input".input);
//console.log("Don't summon".zalgo)

76
node_modules/colors/examples/safe-string.js generated vendored Normal file
View File

@ -0,0 +1,76 @@
var colors = require('../safe');
console.log(colors.yellow("First some yellow text"));
console.log(colors.yellow.underline("Underline that text"));
console.log(colors.red.bold("Make it bold and red"));
console.log(colors.rainbow("Double Raindows All Day Long"))
console.log(colors.trap("Drop the bass"))
console.log(colors.rainbow(colors.trap("DROP THE RAINBOW BASS")));
console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported
console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); // styles not widely supported
console.log(colors.zebra("Zebras are so fun!"));
console.log("This is " + colors.strikethrough("not") + " fun.");
console.log(colors.black.bgWhite('Background color attack!'));
console.log(colors.random('Use random styles on everything!'))
console.log(colors.america('America, Heck Yeah!'));
console.log('Setting themes is useful')
//
// Custom themes
//
//console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
// outputs grey text
console.log(colors.input("this is an input"));
// console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(__dirname + '/../themes/generic-logging.js');
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
// outputs grey text
console.log(colors.input("this is an input"));
// console.log(colors.zalgo("Don't summon him"))

176
node_modules/colors/lib/colors.js generated vendored Normal file
View File

@ -0,0 +1,176 @@
/*
The MIT License (MIT)
Original Library
- Copyright (c) Marak Squires
Additional functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var colors = {};
module['exports'] = colors;
colors.themes = {};
var ansiStyles = colors.styles = require('./styles');
var defineProps = Object.defineProperties;
colors.supportsColor = require('./system/supports-colors');
if (typeof colors.enabled === "undefined") {
colors.enabled = colors.supportsColor;
}
colors.stripColors = colors.strip = function(str){
return ("" + str).replace(/\x1B\[\d+m/g, '');
};
var stylize = colors.stylize = function stylize (str, style) {
return ansiStyles[style].open + str + ansiStyles[style].close;
}
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
}
function build(_styles) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto;
return builder;
}
var styles = (function () {
var ret = {};
ansiStyles.grey = ansiStyles.gray;
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build(this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function colors() {}, styles);
function applyStyle() {
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!colors.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
while (i--) {
var code = ansiStyles[nestedStyles[i]];
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
return str;
}
function applyTheme (theme) {
for (var style in theme) {
(function(style){
colors[style] = function(str){
return colors[theme[style]](str);
};
})(style)
}
}
colors.setTheme = function (theme) {
if (typeof theme === 'string') {
try {
colors.themes[theme] = require(theme);
applyTheme(colors.themes[theme]);
return colors.themes[theme];
} catch (err) {
console.log(err);
return err;
}
} else {
applyTheme(theme);
}
};
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build([name]);
}
};
});
return ret;
}
var sequencer = function sequencer (map, str) {
var exploded = str.split(""), i = 0;
exploded = exploded.map(map);
return exploded.join("");
};
// custom formatter methods
colors.trap = require('./custom/trap');
colors.zalgo = require('./custom/zalgo');
// maps
colors.maps = {};
colors.maps.america = require('./maps/america');
colors.maps.zebra = require('./maps/zebra');
colors.maps.rainbow = require('./maps/rainbow');
colors.maps.random = require('./maps/random')
for (var map in colors.maps) {
(function(map){
colors[map] = function (str) {
return sequencer(colors.maps[map], str);
}
})(map)
}
defineProps(colors, init());

45
node_modules/colors/lib/custom/trap.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
module['exports'] = function runTheTrap (text, options) {
var result = "";
text = text || "Run the trap, drop the bass";
text = text.split('');
var trap = {
a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"],
b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"],
c: ["\u00a9", "\u023b", "\u03fe"],
d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"],
e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"],
f: ["\u04fa"],
g: ["\u0262"],
h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"],
i: ["\u0f0f"],
j: ["\u0134"],
k: ["\u0138", "\u04a0", "\u04c3", "\u051e"],
l: ["\u0139"],
m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"],
n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"],
o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"],
p: ["\u01f7", "\u048e"],
q: ["\u09cd"],
r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"],
s: ["\u00a7", "\u03de", "\u03df", "\u03e8"],
t: ["\u0141", "\u0166", "\u0373"],
u: ["\u01b1", "\u054d"],
v: ["\u05d8"],
w: ["\u0428", "\u0460", "\u047c", "\u0d70"],
x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"],
y: ["\u00a5", "\u04b0", "\u04cb"],
z: ["\u01b5", "\u0240"]
}
text.forEach(function(c){
c = c.toLowerCase();
var chars = trap[c] || [" "];
var rand = Math.floor(Math.random() * chars.length);
if (typeof trap[c] !== "undefined") {
result += trap[c][rand];
} else {
result += c;
}
});
return result;
}

104
node_modules/colors/lib/custom/zalgo.js generated vendored Normal file
View File

@ -0,0 +1,104 @@
// please no
module['exports'] = function zalgo(text, options) {
text = text || " he is here ";
var soul = {
"up" : [
'̍', '̎', '̄', '̅',
'̿', '̑', '̆', '̐',
'͒', '͗', '͑', '̇',
'̈', '̊', '͂', '̓',
'̈', '͊', '͋', '͌',
'̃', '̂', '̌', '͐',
'̀', '́', '̋', '̏',
'̒', '̓', '̔', '̽',
'̉', 'ͣ', 'ͤ', 'ͥ',
'ͦ', 'ͧ', 'ͨ', 'ͩ',
'ͪ', 'ͫ', 'ͬ', 'ͭ',
'ͮ', 'ͯ', '̾', '͛',
'͆', '̚'
],
"down" : [
'̖', '̗', '̘', '̙',
'̜', '̝', '̞', '̟',
'̠', '̤', '̥', '̦',
'̩', '̪', '̫', '̬',
'̭', '̮', '̯', '̰',
'̱', '̲', '̳', '̹',
'̺', '̻', '̼', 'ͅ',
'͇', '͈', '͉', '͍',
'͎', '͓', '͔', '͕',
'͖', '͙', '͚', '̣'
],
"mid" : [
'̕', '̛', '̀', '́',
'͘', '̡', '̢', '̧',
'̨', '̴', '̵', '̶',
'͜', '͝', '͞',
'͟', '͠', '͢', '̸',
'̷', '͡', ' ҉'
]
},
all = [].concat(soul.up, soul.down, soul.mid),
zalgo = {};
function randomNumber(range) {
var r = Math.floor(Math.random() * range);
return r;
}
function is_char(character) {
var bool = false;
all.filter(function (i) {
bool = (i === character);
});
return bool;
}
function heComes(text, options) {
var result = '', counts, l;
options = options || {};
options["up"] = options["up"] || true;
options["mid"] = options["mid"] || true;
options["down"] = options["down"] || true;
options["size"] = options["size"] || "maxi";
text = text.split('');
for (l in text) {
if (is_char(l)) {
continue;
}
result = result + text[l];
counts = {"up" : 0, "down" : 0, "mid" : 0};
switch (options.size) {
case 'mini':
counts.up = randomNumber(8);
counts.min = randomNumber(2);
counts.down = randomNumber(8);
break;
case 'maxi':
counts.up = randomNumber(16) + 3;
counts.min = randomNumber(4) + 1;
counts.down = randomNumber(64) + 3;
break;
default:
counts.up = randomNumber(8) + 1;
counts.mid = randomNumber(6) / 2;
counts.down = randomNumber(8) + 1;
break;
}
var arr = ["up", "mid", "down"];
for (var d in arr) {
var index = arr[d];
for (var i = 0 ; i <= counts[index]; i++) {
if (options[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
// don't summon him
return heComes(text);
}

118
node_modules/colors/lib/extendStringPrototype.js generated vendored Normal file
View File

@ -0,0 +1,118 @@
var colors = require('./colors'),
styles = require('./styles');
module['exports'] = function () {
//
// Extends prototype of native string object to allow for "foo".red syntax
//
var addProperty = function (color, func) {
String.prototype.__defineGetter__(color, func);
};
var sequencer = function sequencer (map, str) {
return function () {
var exploded = this.split(""), i = 0;
exploded = exploded.map(map);
return exploded.join("");
}
};
var stylize = function stylize (str, style) {
return styles[style].open + str + styles[style].close;
}
addProperty('strip', function () {
return colors.strip(this);
});
addProperty('stripColors', function () {
return colors.strip(this);
});
addProperty("trap", function(){
return colors.trap(this);
});
addProperty("zalgo", function(){
return colors.zalgo(this);
});
addProperty("zebra", function(){
return colors.zebra(this);
});
addProperty("rainbow", function(){
return colors.rainbow(this);
});
addProperty("random", function(){
return colors.random(this);
});
addProperty("america", function(){
return colors.america(this);
});
//
// Iterate through all default styles and colors
//
var x = Object.keys(colors.styles);
x.forEach(function (style) {
addProperty(style, function () {
return stylize(this, style);
});
});
function applyTheme(theme) {
//
// Remark: This is a list of methods that exist
// on String that you should not overwrite.
//
var stringPrototypeBlacklist = [
'__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor',
'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt',
'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring',
'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight'
];
Object.keys(theme).forEach(function (prop) {
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name');
}
else {
if (typeof(theme[prop]) === 'string') {
colors[prop] = colors[theme[prop]];
addProperty(prop, function () {
return colors[theme[prop]](this);
});
}
else {
addProperty(prop, function () {
var ret = this;
for (var t = 0; t < theme[prop].length; t++) {
ret = exports[theme[prop][t]](ret);
}
return ret;
});
}
}
});
}
colors.setTheme = function (theme) {
if (typeof theme === 'string') {
try {
colors.themes[theme] = require(theme);
applyTheme(colors.themes[theme]);
return colors.themes[theme];
} catch (err) {
console.log(err);
return err;
}
} else {
applyTheme(theme);
}
};
};

12
node_modules/colors/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
var colors = require('./colors');
module['exports'] = colors;
// Remark: By default, colors will add style properties to String.prototype
//
// If you don't wish to extend String.prototype you can do this instead and native String will not be touched
//
// var colors = require('colors/safe);
// colors.red("foo")
//
//
var extendStringPrototype = require('./extendStringPrototype')();

12
node_modules/colors/lib/maps/america.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
var colors = require('../colors');
module['exports'] = (function() {
return function (letter, i, exploded) {
if(letter === " ") return letter;
switch(i%3) {
case 0: return colors.red(letter);
case 1: return colors.white(letter)
case 2: return colors.blue(letter)
}
}
})();

13
node_modules/colors/lib/maps/rainbow.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
var colors = require('../colors');
module['exports'] = (function () {
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV
return function (letter, i, exploded) {
if (letter === " ") {
return letter;
} else {
return colors[rainbowColors[i++ % rainbowColors.length]](letter);
}
};
})();

8
node_modules/colors/lib/maps/random.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
var colors = require('../colors');
module['exports'] = (function () {
var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];
return function(letter, i, exploded) {
return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter);
};
})();

5
node_modules/colors/lib/maps/zebra.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
var colors = require('../colors');
module['exports'] = function (letter, i, exploded) {
return i % 2 === 0 ? letter : colors.inverse(letter);
};

77
node_modules/colors/lib/styles.js generated vendored Normal file
View File

@ -0,0 +1,77 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var styles = {};
module['exports'] = styles;
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
grey: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// legacy styles for colors pre v1.0.0
blackBG: [40, 49],
redBG: [41, 49],
greenBG: [42, 49],
yellowBG: [43, 49],
blueBG: [44, 49],
magentaBG: [45, 49],
cyanBG: [46, 49],
whiteBG: [47, 49]
};
Object.keys(codes).forEach(function (key) {
var val = codes[key];
var style = styles[key] = [];
style.open = '\u001b[' + val[0] + 'm';
style.close = '\u001b[' + val[1] + 'm';
});

61
node_modules/colors/lib/system/supports-colors.js generated vendored Normal file
View File

@ -0,0 +1,61 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var argv = process.argv;
module.exports = (function () {
if (argv.indexOf('--no-color') !== -1 ||
argv.indexOf('--color=false') !== -1) {
return false;
}
if (argv.indexOf('--color') !== -1 ||
argv.indexOf('--color=true') !== -1 ||
argv.indexOf('--color=always') !== -1) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();

79
node_modules/colors/package.json generated vendored Normal file
View File

@ -0,0 +1,79 @@
{
"_args": [
[
"colors@1.0.x",
"/Users/akira/src/biomedjs/node_modules/winston"
]
],
"_from": "colors@>=1.0.0 <1.1.0",
"_id": "colors@1.0.3",
"_inCache": true,
"_installable": true,
"_location": "/colors",
"_nodeVersion": "0.11.13",
"_npmUser": {
"email": "marak.squires@gmail.com",
"name": "marak"
},
"_npmVersion": "2.0.2",
"_phantomChildren": {},
"_requested": {
"name": "colors",
"raw": "colors@1.0.x",
"rawSpec": "1.0.x",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/winston"
],
"_resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz",
"_shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b",
"_shrinkwrap": null,
"_spec": "colors@1.0.x",
"_where": "/Users/akira/src/biomedjs/node_modules/winston",
"author": {
"name": "Marak Squires"
},
"bugs": {
"url": "https://github.com/Marak/colors.js/issues"
},
"dependencies": {},
"description": "get colors in your node.js console",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b",
"tarball": "http://registry.npmjs.org/colors/-/colors-1.0.3.tgz"
},
"engines": {
"node": ">=0.1.90"
},
"gitHead": "e9e6557cc0fa26dba1a20b0d45e92de982f4047c",
"homepage": "https://github.com/Marak/colors.js",
"keywords": [
"ansi",
"colors",
"terminal"
],
"license": "MIT",
"main": "./lib/index",
"maintainers": [
{
"name": "marak",
"email": "marak.squires@gmail.com"
}
],
"name": "colors",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/Marak/colors.js.git"
},
"scripts": {
"test": "node tests/basic-test.js && node tests/safe-test.js"
},
"version": "1.0.3"
}

9
node_modules/colors/safe.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
//
// Remark: Requiring this file will use the "safe" colors API which will not touch String.prototype
//
// var colors = require('colors/safe);
// colors.red("foo")
//
//
var colors = require('./lib/colors');
module['exports'] = colors;

BIN
node_modules/colors/screenshots/colors.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

50
node_modules/colors/tests/basic-test.js generated vendored Normal file
View File

@ -0,0 +1,50 @@
var assert = require('assert'),
colors = require('../lib/index');
var s = 'string';
function a(s, code) {
return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m';
}
function aE(s, color, code) {
assert.equal(s[color], a(s, code));
assert.equal(colors[color](s), a(s, code));
assert.equal(s[color], colors[color](s));
assert.equal(s[color].strip, s);
assert.equal(s[color].strip, colors.strip(s));
}
function h(s, color) {
return '<span style="color:' + color + ';">' + s + '</span>';
}
var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow'];
var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']);
colors.mode = 'console';
assert.equal(s.bold, '\x1B[1m' + s + '\x1B[22m');
assert.equal(s.italic, '\x1B[3m' + s + '\x1B[23m');
assert.equal(s.underline, '\x1B[4m' + s + '\x1B[24m');
assert.equal(s.strikethrough, '\x1B[9m' + s + '\x1B[29m');
assert.equal(s.inverse, '\x1B[7m' + s + '\x1B[27m');
assert.ok(s.rainbow);
aE(s, 'white', 37);
aE(s, 'grey', 90);
aE(s, 'black', 30);
aE(s, 'blue', 34);
aE(s, 'cyan', 36);
aE(s, 'green', 32);
aE(s, 'magenta', 35);
aE(s, 'red', 31);
aE(s, 'yellow', 33);
assert.equal(s, 'string');
colors.setTheme({error:'red'});
assert.equal(typeof("astring".red),'string');
assert.equal(typeof("astring".error),'string');

45
node_modules/colors/tests/safe-test.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
var assert = require('assert'),
colors = require('../safe');
var s = 'string';
function a(s, code) {
return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m';
}
function aE(s, color, code) {
assert.equal(colors[color](s), a(s, code));
assert.equal(colors.strip(s), s);
}
function h(s, color) {
return '<span style="color:' + color + ';">' + s + '</span>';
}
var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow'];
var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']);
colors.mode = 'console';
assert.equal(colors.bold(s), '\x1B[1m' + s + '\x1B[22m');
assert.equal(colors.italic(s), '\x1B[3m' + s + '\x1B[23m');
assert.equal(colors.underline(s), '\x1B[4m' + s + '\x1B[24m');
assert.equal(colors.strikethrough(s), '\x1B[9m' + s + '\x1B[29m');
assert.equal(colors.inverse(s), '\x1B[7m' + s + '\x1B[27m');
assert.ok(colors.rainbow);
aE(s, 'white', 37);
aE(s, 'grey', 90);
aE(s, 'black', 30);
aE(s, 'blue', 34);
aE(s, 'cyan', 36);
aE(s, 'green', 32);
aE(s, 'magenta', 35);
aE(s, 'red', 31);
aE(s, 'yellow', 33);
assert.equal(s, 'string');
colors.setTheme({error:'red'});
assert.equal(typeof(colors.red("astring")), 'string');
assert.equal(typeof(colors.error("astring")), 'string');

12
node_modules/colors/themes/generic-logging.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
module['exports'] = {
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
};

49
node_modules/cycle/README.md generated vendored Normal file
View File

@ -0,0 +1,49 @@
Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`.
# Contributors
* Douglas Crockford
* Nuno Job
* Justin Warkentin
# JSON in JavaScript
Douglas Crockford
douglas@crockford.com
2010-11-18
JSON is a light-weight, language independent, data interchange format.
See http://www.JSON.org/
The files in this collection implement JSON encoders/decoders in JavaScript.
JSON became a built-in feature of JavaScript when the ECMAScript Programming
Language Standard - Fifth Edition was adopted by the ECMA General Assembly
in December 2009. Most of the files in this collection are for applications
that are expected to run in obsolete web browsers. For most purposes, json2.js
is the best choice.
json2.js: This file creates a JSON property in the global object, if there
isn't already one, setting its value to an object containing a stringify
method and a parse method. The parse method uses the eval method to do the
parsing, guarding it with several regular expressions to defend against
accidental code execution hazards. On current browsers, this file does nothing,
prefering the built-in JSON object.
json.js: This file does everything that json2.js does. It also adds a
toJSONString method and a parseJSON method to Object.prototype. Use of this
file is not recommended.
json_parse.js: This file contains an alternative JSON parse function that
uses recursive descent instead of eval.
json_parse_state.js: This files contains an alternative JSON parse function that
uses a state machine instead of eval.
cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle,
which make it possible to encode cyclical structures and dags in JSON, and to
then recover them. JSONPath is used to represent the links.
http://GOESSNER.net/articles/JsonPath/

170
node_modules/cycle/cycle.js generated vendored Normal file
View File

@ -0,0 +1,170 @@
/*
cycle.js
2013-02-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*jslint evil: true, regexp: true */
/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push,
retrocycle, stringify, test, toString
*/
var cycle = exports;
cycle.decycle = function decycle(object) {
'use strict';
// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form
// {$ref: PATH}
// where the PATH is a JSONPath string that locates the first occurance.
// So,
// var a = [];
// a[0] = a;
// return JSON.stringify(JSON.decycle(a));
// produces the string '[{"$ref":"$"}]'.
// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child member or
// property.
var objects = [], // Keep a reference to each unique object or array
paths = []; // Keep the path to each unique object or array
return (function derez(value, path) {
// The derez recurses through the object, producing the deep copy.
var i, // The loop counter
name, // Property name
nu; // The new object or array
// typeof null === 'object', so go on if this value is really an object but not
// one of the weird builtin objects.
if (typeof value === 'object' && value !== null &&
!(value instanceof Boolean) &&
!(value instanceof Date) &&
!(value instanceof Number) &&
!(value instanceof RegExp) &&
!(value instanceof String)) {
// If the value is an object or array, look to see if we have already
// encountered it. If so, return a $ref/path object. This is a hard way,
// linear search that will get slower as the number of unique objects grows.
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return {$ref: paths[i]};
}
}
// Otherwise, accumulate the unique value and its path.
objects.push(value);
paths.push(path);
// If it is an array, replicate the array.
if (Object.prototype.toString.apply(value) === '[object Array]') {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = derez(value[i], path + '[' + i + ']');
}
} else {
// If it is an object, replicate the object.
nu = {};
for (name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
nu[name] = derez(value[name],
path + '[' + JSON.stringify(name) + ']');
}
}
}
return nu;
}
return value;
}(object, '$'));
};
cycle.retrocycle = function retrocycle($) {
'use strict';
// Restore an object that was reduced by decycle. Members whose values are
// objects of the form
// {$ref: PATH}
// are replaced with references to the value found by the PATH. This will
// restore cycles. The object will be mutated.
// The eval function is used to locate the values described by a PATH. The
// root object is kept in a $ variable. A regular expression is used to
// assure that the PATH is extremely well formed. The regexp contains nested
// * quantifiers. That has been known to have extremely bad performance
// problems on some browsers for very long strings. A PATH is expected to be
// reasonably short. A PATH is allowed to belong to a very restricted subset of
// Goessner's JSONPath.
// So,
// var s = '[{"$ref":"$"}]';
// return JSON.retrocycle(JSON.parse(s));
// produces an array containing a single element which is the array itself.
var px =
/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;
(function rez(value) {
// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[i] = eval(path);
} else {
rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[name] = eval(path);
} else {
rez(item);
}
}
}
}
}
}
}($));
return $;
};

73
node_modules/cycle/package.json generated vendored Normal file
View File

@ -0,0 +1,73 @@
{
"_args": [
[
"cycle@1.0.x",
"/Users/akira/src/biomedjs/node_modules/winston"
]
],
"_from": "cycle@>=1.0.0 <1.1.0",
"_id": "cycle@1.0.3",
"_inCache": true,
"_installable": true,
"_location": "/cycle",
"_npmUser": {
"email": "nunojobpinto@gmail.com",
"name": "dscape"
},
"_npmVersion": "1.2.32",
"_phantomChildren": {},
"_requested": {
"name": "cycle",
"raw": "cycle@1.0.x",
"rawSpec": "1.0.x",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/winston"
],
"_resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz",
"_shasum": "21e80b2be8580f98b468f379430662b046c34ad2",
"_shrinkwrap": null,
"_spec": "cycle@1.0.x",
"_where": "/Users/akira/src/biomedjs/node_modules/winston",
"author": "",
"bugs": {
"url": "http://github.com/douglascrockford/JSON-js/issues"
},
"dependencies": {},
"description": "decycle your json",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "21e80b2be8580f98b468f379430662b046c34ad2",
"tarball": "http://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz"
},
"engines": {
"node": ">=0.4.0"
},
"homepage": "https://github.com/douglascrockford/JSON-js",
"keywords": [
"cycle",
"json",
"parse",
"stringify"
],
"main": "./cycle.js",
"maintainers": [
{
"name": "dscape",
"email": "nunojobpinto@gmail.com"
}
],
"name": "cycle",
"optionalDependencies": {},
"readme": "Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`.\n\n# Contributors\n\n* Douglas Crockford\n* Nuno Job\n* Justin Warkentin\n\n# JSON in JavaScript\n\nDouglas Crockford\ndouglas@crockford.com\n\n2010-11-18\n\n\nJSON is a light-weight, language independent, data interchange format.\nSee http://www.JSON.org/\n\nThe files in this collection implement JSON encoders/decoders in JavaScript.\n\nJSON became a built-in feature of JavaScript when the ECMAScript Programming\nLanguage Standard - Fifth Edition was adopted by the ECMA General Assembly\nin December 2009. Most of the files in this collection are for applications\nthat are expected to run in obsolete web browsers. For most purposes, json2.js\nis the best choice.\n\n\njson2.js: This file creates a JSON property in the global object, if there\nisn't already one, setting its value to an object containing a stringify\nmethod and a parse method. The parse method uses the eval method to do the\nparsing, guarding it with several regular expressions to defend against\naccidental code execution hazards. On current browsers, this file does nothing,\nprefering the built-in JSON object.\n\njson.js: This file does everything that json2.js does. It also adds a\ntoJSONString method and a parseJSON method to Object.prototype. Use of this\nfile is not recommended.\n\njson_parse.js: This file contains an alternative JSON parse function that\nuses recursive descent instead of eval.\n\njson_parse_state.js: This files contains an alternative JSON parse function that\nuses a state machine instead of eval.\n\ncycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle,\nwhich make it possible to encode cyclical structures and dags in JSON, and to\nthen recover them. JSONPath is used to represent the links.\nhttp://GOESSNER.net/articles/JsonPath/\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/dscape/cycle.git"
},
"version": "1.0.3"
}

11
node_modules/express-validator/.editorconfig generated vendored Normal file
View File

@ -0,0 +1,11 @@
# This file is for unifying the coding style for different editors and IDEs.
# More information at http://EditorConfig.org
# No .editorconfig files above the root directory
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true

56
node_modules/express-validator/.jscsrc generated vendored Normal file
View File

@ -0,0 +1,56 @@
{
"excludeFiles": ["node_modules/**"],
"disallowEmptyBlocks": true,
"disallowKeywordsOnNewLine": ["else"],
"disallowKeywords": ["with"],
"disallowMixedSpacesAndTabs": true,
"disallowNewlineBeforeBlockStatements": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"disallowSpaceBeforeBinaryOperators": [","],
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
"disallowSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInCallExpression": true,
"disallowSpacesInFunctionDeclaration": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInNamedFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowTrailingComma": true,
"disallowTrailingWhitespace": true,
"requireCommaBeforeLineBreak": true,
"requireCurlyBraces": [
"if",
"else",
"for",
"while",
"do",
"try",
"catch"
],
"requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"],
"requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"],
"requireSpaceBeforeKeywords": [
"else",
"while",
"catch"
],
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"],
"requireSpaceBeforeObjectValues": true,
"requireSpaceBetweenArguments": true,
"requireSpacesInConditionalExpression": {
"afterTest": true,
"beforeConsequent": true,
"afterConsequent": true,
"beforeAlternate": true
},
"requireSpacesInForStatement": true,
"requireSpacesInFunction": {
"beforeOpeningCurlyBrace": true
},
"requireSpacesInsideObjectBrackets": "all",
"validateParameterSeparator": ", "
}

18
node_modules/express-validator/.jshintrc generated vendored Normal file
View File

@ -0,0 +1,18 @@
{
"regexdash": true,
"browser": true,
"trailing": true,
"sub": true,
"curly": true,
"eqeqeq": true,
"indent": 4,
"latedef": "nofunc",
"newcap": true,
"unused": true,
"eqnull": true,
"bitwise": true,
"noarg": true,
"noempty": true,
"nonew": true,
"node": true
}

Some files were not shown because too many files have changed in this diff Show More