chocolate
Version:
A full stack Node.js web framework built using Coffeescript
1,500 lines (1,495 loc) • 88.6 kB
JavaScript
// Generated by CoffeeScript 1.12.6
(function() {
var Log, _defaults, _module, lateDB, loadedDBs,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
hasProp = {}.hasOwnProperty;
loadedDBs = {};
_defaults = {
filename: 'db.log',
datadir: '.'
};
Log = function() {
var BufferStream, Fs, Path, _, _datadir, _db, _exists, _filename, _flushed, _loaded, _modules, _op_index, _ops, _path_index, _pathname, _paths, _queue, clear, compact, ensure, filename, flush, flushed, forget, init, io, keyname, load, loaded, module_, parse, pathname, register, require_db, revert, stringify, update, update_one, upgrade, write;
Fs = void 0;
BufferStream = void 0;
Path = void 0;
_ = void 0;
_exists = false;
_flushed = [];
_loaded = false;
_db = {};
_ops = [];
_op_index = {};
_paths = [];
_path_index = {};
_modules = {};
_queue = '';
if (typeof window === "undefined" || window === null) {
_defaults.datadir = require('chocolate/server/document').datadir;
}
_datadir = _defaults.datadir;
_filename = _defaults.filename;
_pathname = null;
setTimeout((function() {
return flush();
}), 100);
init = function(current, options) {
var f, func_str, module, returns, var_str;
if (current == null) {
current = '';
}
if (options == null) {
options = {};
}
module = options.module, var_str = options.var_str;
if (module == null) {
module = false;
}
if (typeof current === 'object' && (current._db != null)) {
var_str = "var _db = " + (stringify(current._db, {
mode: 'json'
})) + ",\n_o = [" + (((function() {
var j, len, ref, results;
ref = current._ops;
results = [];
for (j = 0, len = ref.length; j < len; j++) {
f = ref[j];
results.push(f.toString());
}
return results;
})()).join(',')) + "],\n_oi = " + (stringify(current._op_index, {
mode: 'json'
})) + ",\n_p = " + (stringify(current._paths, {
mode: 'json'
})) + ",\n_pi = " + (stringify(current._path_index, {
mode: 'json'
})) + ",\n_m = " + (stringify(current._modules)) + ",\np, op;";
current = '';
} else {
if (var_str == null) {
var_str = "var _db = {},\n_o = [],\n_oi = {},\n_p = [],\n_pi = {},\n_m = {},\np, op;";
}
}
if (options.alias) {
var_str += "_o = _ops;\n_oi = _op_index;\n_p = _paths;\n_pi = _path_index;\n_m = _modules;";
}
if (options.rebuild) {
var_str += (options.alias ? '\n' : '') + "if (_oi === null) {\n var i, len;\n _oi = {};\n for (i = 0, len = _o.length; i < len; i++) {\n _oi[_o[i].toString()] = i;\n }\n " + (options.alias ? "_op_index = _oi;" : "") + "\n};";
}
func_str = "var _ = function(oi, pi, data) {\n var i, len, node, op, path, step, steps;\n op = _o[oi];\n path = _p[pi];\n node = _db;\n steps = path.split('.');\n for (i = 0, len = steps.length; i < len; i++) {\n step = steps[i];\n if (node[step] == null) {\n node[step] = {};\n }\n node = node[step];\n }\n op.call(node, data, _m);\n};";
returns = typeof window !== "undefined" && window !== null ? var_str + "\n" + func_str + "\n" + current : var_str + "\n" + func_str + "\nmodule.exports = {\n_db:_db,\n_ops:_o,\n_op_index:_oi,\n_paths:_p,\n_path_index:_pi,\n_modules:_m\n};";
if (module) {
returns = "(function () {\n " + returns + "\n return {_db:_db,_ops:_o,_op_index:_oi,_paths:_p,_path_index:_pi,_modules:_m}\n})()";
}
return returns + '\n';
};
keyname = function(name) {
if (name != null) {
return 'LateDB-' + name;
} else {
return 'LateDB-' + filename();
}
};
filename = function(name) {
if (name != null) {
_filename = name;
}
return _filename;
};
pathname = function(name, path) {
if (path != null) {
_datadir = path;
}
if (name == null) {
if (_pathname == null) {
_pathname = _datadir + '/' + _filename;
}
return _pathname;
} else {
return _datadir + '/' + name;
}
};
ensure = function(path) {
var j, len, node, step, steps;
node = _db;
steps = path.split('.');
for (j = 0, len = steps.length; j < len; j++) {
step = steps[j];
if (!(node != null)) {
continue;
}
if (node[step] == null) {
node[step] = {};
}
node = node[step];
}
return node;
};
stringify = function() {
var array_as_object, concat, doit, newline, object, options, ref, tab, write;
if (arguments.length === 0) {
return void 0;
}
object = arguments[0];
options = (ref = arguments[1]) != null ? ref : {};
if (options.prettify === true) {
tab = ' ';
newline = '\n';
} else {
tab = newline = '';
}
array_as_object = false;
switch (options.mode) {
case 'json':
return JSON.stringify(object, null, tab);
case 'full':
array_as_object = true;
break;
case 'js':
}
write = typeof options.write === 'function' ? options.write : function(str) {
return str;
};
concat = function(w1, w2, w3) {
if ((w1 != null) && (w2 != null) && (w3 != null)) {
return w1 + w2 + w3;
} else {
return null;
}
};
doit = function(o, level, index) {
var chunk, i, indent, k, ni, nit, sep, type, v;
if (level == null) {
level = 0;
}
indent = tab === '' ? '' : ((function() {
var j, ref1, results;
results = [];
for (j = 0, ref1 = level; 0 <= ref1 ? j < ref1 : j > ref1; 0 <= ref1 ? j++ : j--) {
results.push(tab);
}
return results;
})()).join('');
ni = newline + indent;
nit = ni + tab;
type = Object.prototype.toString.apply(o);
sep = index > 0 ? ',' + nit : '';
switch (type) {
case '[object Object]':
if (o.constructor !== {}.constructor && (o.stringify != null) && typeof o.stringify === 'function') {
return write(sep + o.stringify());
} else {
if (o.constructor !== {}.constructor && options.strict) {
throw "_.stringify in strict mode can only accept pure objects";
} else {
i = 0;
return concat(write(sep + ("" + (options.variable && level === 0 ? 'var ' : '{') + nit)), "" + (((function() {
var ref1, results;
results = [];
for (k in o) {
v = o[k];
if (((options.filter == null) || (ref1 = v.constructor, indexOf.call(options.filter, ref1) >= 0)) && (options.own !== true || {}.hasOwnProperty.call(o, k)) && (chunk = write((i++ > 0 ? ',' + nit : '') + (options.variable && level === 0 ? k : "'" + k.toString().replace(/\'/g, "\\'") + "'") + (options.variable && level === 0 ? '=' : ':')) + doit(v, level + 1))) {
results.push(chunk);
}
}
return results;
})()).join('')), write("" + ni + (options.variable && level === 0 ? ';' : '}')));
}
}
break;
case '[object Array]':
if (array_as_object) {
i = 0;
return concat(write(sep + ("function () {" + nit + "var a = []; var o = {" + nit)), "" + (((function() {
var results;
results = [];
for (k in o) {
if (!hasProp.call(o, k)) continue;
v = o[k];
if ((chunk = write((i++ > 0 ? ',' + nit : '') + k + ':') + doit(v, level + 1))) {
results.push(chunk);
}
}
return results;
})()).join('')), write("};" + nit + "for (var k in o) {a[k] = o[k];} return a; }()"));
} else {
return concat(write(sep + ("[" + nit)), "" + (((function() {
var j, len, results;
results = [];
for (i = j = 0, len = o.length; j < len; i = ++j) {
v = o[i];
if ((chunk = doit(v, level + 1, i)) != null) {
results.push(chunk);
}
}
return results;
})()).join('')), write(ni + "]"));
}
break;
case '[object Boolean]':
return write(sep + o);
case '[object Number]':
return write(sep + o);
case '[object Date]':
return write(sep + ("new Date(" + (o.valueOf()) + ")"));
case '[object Function]':
return write(sep + o.toString());
case '[object Math]':
return write(sep + 'Math');
case '[object String]':
return write(sep + ("'" + (o.replace(/\'/g, '\\\'')) + "'"));
case '[object Undefined]':
return write(sep + 'void 0');
case '[object Null]':
return write(sep + 'null');
case '[object Buffer]':
case '[object SlowBuffer]':
return write(sep + (o.length === 16 ? require('chocolate/general/chocodash').Uuid.unparse(o) : o.toString()));
}
};
return doit(object);
};
require_db = function(name) {
var required, result;
if (Path == null) {
Path = require('path');
}
required = Path.resolve(pathname(name != null ? name : _filename));
delete require.cache[required];
result = require(required);
return result;
};
load = function(initial_queue) {
var current, ref, ref1;
_queue = '';
if (initial_queue == null) {
initial_queue = '';
}
if (typeof window !== "undefined" && window !== null) {
current = localStorage.getItem(keyname());
if ((current != null) && current !== "") {
ref = eval(init(current, {
module: true
})), _db = ref._db, _ops = ref._ops, _op_index = ref._op_index, _paths = ref._paths, _path_index = ref._path_index, _modules = ref._modules;
}
_queue = initial_queue;
} else {
if (Fs == null) {
Fs = require('fs');
}
if (Fs.existsSync(pathname())) {
ref1 = require_db(), _db = ref1._db, _ops = ref1._ops, _op_index = ref1._op_index, _paths = ref1._paths, _path_index = ref1._path_index, _modules = ref1._modules;
} else {
_queue = init();
}
_queue += (_queue !== '' ? '\n' : '') + initial_queue;
}
_exists = true;
return _loaded = true;
};
loaded = function() {
return _loaded;
};
io = function(path, data, op) {
var j, len, node, step, steps, updates;
if (typeof path !== 'string') {
return _db;
}
if (arguments.length === 3) {
updates = {};
updates[path] = {
data: data,
op: op
};
return update(updates);
}
node = _db;
steps = path.split('.');
for (j = 0, len = steps.length; j < len; j++) {
step = steps[j];
if (!(node != null)) {
continue;
}
if (node[step] == null) {
return null;
}
node = node[step];
}
return node;
};
write = function(op_index, path_index, data) {
var op, path;
switch (arguments.length) {
case 0:
return _queue += "// " + (Date.now().valueOf()) + "\n";
case 2:
if (typeof path_index === 'string') {
path = path_index;
return _queue += "p='" + path + "';\n_pi[p]=_p.push(p)-1;\n";
} else {
op = path_index;
return _queue += "op=" + (op.toString().replace(/^\/\/.*(\n)*/mg, '')) + ";\n_oi[op.toString()]=_o.push(op)-1;\n";
}
break;
default:
return _queue += "_(" + op_index + "," + path_index + "," + (JSON.stringify(data)) + ");\n";
}
};
update_one = function(path, data, op) {
var op_hash, op_index, path_index;
op_hash = op.toString();
op_index = _op_index[op_hash];
if (op_index == null) {
op_index = _op_index[op_hash] = -1 + _ops.push(op);
write(op_index, op);
}
path_index = _path_index[path];
if (path_index == null) {
path_index = _path_index[path] = -1 + _paths.push(path);
write(op_index, path);
}
write(op_index, path_index, data);
op.call(ensure(path), data, _modules);
};
update = function() {
var data, op, path, ref, updates;
write();
if (arguments.length === 2) {
if (typeof arguments[1] === 'function') {
updates = arguments[0], op = arguments[1];
for (path in updates) {
data = updates[path];
update_one(path, data, op);
}
} else {
data = arguments[0], updates = arguments[1];
for (path in updates) {
op = updates[path];
update_one(path, data, op);
}
}
} else {
updates = arguments[0];
for (path in updates) {
ref = updates[path], data = ref.data, op = ref.op;
update_one(path, data, op);
}
}
};
flush = function() {
var current;
if (_queue.length > 0) {
if (!_exists) {
load(_queue);
}
if (typeof window !== "undefined" && window !== null) {
current = localStorage.getItem(keyname());
localStorage.setItem(keyname(), (current != null ? current : "") + _queue);
setTimeout((function() {
var f, j, len;
for (j = 0, len = _flushed.length; j < len; j++) {
f = _flushed[j];
f();
}
}), 10);
setTimeout((function() {
return flush();
}), 100);
} else {
Fs.appendFile(pathname(), _queue, function() {
var f, j, len;
for (j = 0, len = _flushed.length; j < len; j++) {
f = _flushed[j];
f();
}
return setTimeout((function() {
return flush();
}), 100);
});
}
_queue = "";
} else {
setTimeout((function() {
return flush();
}), 100);
}
};
forget = function(callback) {
_queue = "";
if (typeof window !== "undefined" && window !== null) {
localStorage.removeItem(keyname());
_exists = false;
if (typeof callback === "function") {
callback();
}
} else {
Fs.unlink(pathname(), function() {
_exists = false;
return typeof callback === "function" ? callback() : void 0;
});
}
};
clear = function(options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
_db = {};
_ops = [];
_op_index = {};
_paths = [];
_path_index = {};
_modules = {};
if (options != null ? options.forget : void 0) {
forget(function() {
_loaded = false;
return typeof callback === "function" ? callback() : void 0;
});
} else {
setTimeout((function() {
_loaded = false;
return typeof callback === "function" ? callback() : void 0;
}), 10);
}
};
register = function(name, service) {
var do_register;
do_register = function(n, f, p, m) {
var k, results, s, v;
if (f == null) {
m[n] = require(name);
_queue += "_m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"] = require('" + name + "');\n";
} else if (typeof f === 'function') {
m[n] = f;
_queue += "_m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"] = (function (" + name + ") { return " + (f.toString().replace(/^\/\/.*(\n)*/mg, '')) + "; })(_m[\"" + name + "\"])\n";
} else {
m[n] = {};
_queue += "_m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"] = {};\n";
}
if (f != null) {
results = [];
for (k in f) {
if (!hasProp.call(f, k)) continue;
v = f[k];
results.push(do_register(k, v, p + (p === '' ? '' : '.') + n, m[n]));
}
return results;
}
};
write();
do_register(name, service, "", _modules);
return _modules[name];
};
upgrade = function(name, service) {
var current, do_append, do_remove, timestamped;
current = _modules[name];
timestamped = false;
do_remove = function(n, f, p, m) {
var k, ref, s;
if ((m[n] != null) && (f == null)) {
delete m[n];
if (!timestamped) {
write();
timestamped = true;
}
_queue += "delete _m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"];\n";
}
if ((m[n] != null) && (f != null)) {
ref = m[n];
for (k in ref) {
if (!hasProp.call(ref, k)) continue;
do_remove(k, f[k], p + (p === '' ? '' : '.') + n, m[n]);
}
}
};
do_append = function(n, f, p, m, force) {
var k, req, s, v;
if (f == null) {
if (m[n] !== (req = require(name))) {
m[n] = req;
if (!timestamped) {
write();
timestamped = true;
}
_queue += "_m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"] = require('" + name + "');\n";
}
} else if (typeof f === 'function') {
if (force || (m[n] == null) || (m[n].toString().replace(/(^\/\/.*(\n)*)|(\r)/mg, '') !== f.toString().replace(/(^\/\/.*(\n)*)|(\r)/mg, ''))) {
m[n] = f;
if (!timestamped) {
write();
timestamped = true;
}
_queue += "_m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"] = (function (" + name + ") { return " + (f.toString().replace(/^\/\/.*(\n)*/mg, '')) + "; })(_m[\"" + name + "\"])\n";
force = true;
}
} else {
if (m[n] == null) {
m[n] = {};
if (!timestamped) {
write();
timestamped = true;
}
_queue += "_m" + ((function() {
var j, len, ref, results;
if (p !== '') {
ref = p.split('.');
results = [];
for (j = 0, len = ref.length; j < len; j++) {
s = ref[j];
results.push('["' + s + '"]');
}
return results;
} else {
return '';
}
})()) + "[\"" + n + "\"] = {};\n";
}
}
if (f != null) {
for (k in f) {
if (!hasProp.call(f, k)) continue;
v = f[k];
do_append(k, v, p + (p === '' ? '' : '.') + n, m[n], force);
}
}
};
do_remove(name, service, "", _modules);
do_append(name, service, "", _modules);
return _modules[name];
};
module_ = function(name) {
return _modules[name];
};
parse = function(context, time_limit, only_after) {
var items, time;
if (only_after == null) {
only_after = false;
}
if (context.after == null) {
context.after = false;
}
if (context.line[0] === '/' && context.line[1] === '/') {
items = context.line.split(' ');
time = parseInt(items[1]);
if ((time_limit != null) && time > time_limit) {
context.after = true;
}
}
if ((!only_after && context.after) || (only_after && !context.after)) {
return false;
}
if (context.log != null) {
context.log += context.line + '\n';
}
return true;
};
revert = function(time, callback) {
var buffer, bytes, context, current, i, j, len, line, lines, readStream;
if (typeof window !== "undefined" && window !== null) {
context = {
log: ''
};
current = localStorage.getItem(keyname());
lines = current.split('\n');
for (i = j = 0, len = lines.length; j < len; i = ++j) {
line = lines[i];
context.line = line;
context.index = i;
if (!parse(context, time)) {
break;
}
}
localStorage.setItem(keyname(), context.log);
load();
if (callback != null) {
setTimeout(callback, 10);
}
} else {
context = {};
if (BufferStream == null) {
BufferStream = require('bufferstream');
}
buffer = new BufferStream({
size: 'flexible',
split: '\n'
});
i = 0;
bytes = 0;
buffer.on('data', function(chunk) {
context.line = chunk.toString();
context.index = i++;
if (!parse(context, time)) {
return readStream.unpipe();
} else {
return bytes += 1 + Buffer.byteLength(context.line, 'utf8');
}
});
buffer.on('unpipe', function() {
return clear(function() {
return Fs.truncate(pathname(), bytes, function() {
load();
return typeof callback === "function" ? callback() : void 0;
});
});
});
readStream = Fs.createReadStream(pathname());
readStream.on('open', function() {
return readStream.pipe(buffer);
});
}
};
compact = function(time, options, callback) {
var context, copy, current, i, j, len, line, lines, now, only_after, page_size, ref, should_compact, temp_filename;
if (typeof options === 'function') {
callback = options;
options = time;
time = null;
}
if (typeof time === 'function') {
callback = time;
options = null;
time = null;
}
if (typeof window !== "undefined" && window !== null) {
context = {
log: ''
};
current = localStorage.getItem(keyname());
lines = current.split('\n');
context.compacted = false;
only_after = false;
for (i = j = 0, len = lines.length; j < len; i = ++j) {
line = lines[i];
context.line = line;
context.index = i;
should_compact = !parse(context, time, only_after);
if ((time == null) && i + 1 === lines.length) {
should_compact = true;
}
if (should_compact) {
if (!context.compacted) {
context.compacted = true;
context.log = init(eval(init(context.log, {
module: true
})));
only_after = true;
parse(context, time, only_after);
}
}
}
localStorage.setItem(keyname(), context.log);
load();
if (callback != null) {
setTimeout(callback, 10);
}
} else {
page_size = (ref = options != null ? options.page_size : void 0) != null ? ref : 128 * 1024;
temp_filename = [(now = new Date()).getFullYear(), (now.getMonth() + 1 < 10 ? '0' : '') + (now.getMonth() + 1), (now.getDate() < 10 ? '0' : '') + now.getDate(), '-', process.pid, '-', (Math.random() * 0x100000000 + 1).toString(36)].join('');
copy = function(context, options, callback) {
var buffer, readStream;
if (typeof options === 'function') {
callback = options;
options = null;
}
if (options == null) {
options = {
append: false
};
}
if (options.append && (time == null)) {
setTimeout((function() {
return callback();
}), 10);
return;
}
if (BufferStream == null) {
BufferStream = require('bufferstream');
}
buffer = new BufferStream({
size: 'flexible',
split: '\n'
});
i = 0;
buffer.on('data', function(chunk) {
context.line = chunk.toString();
context.index = i++;
if (!parse(context, time, options.append)) {
if (!options.append) {
return readStream.unpipe();
}
} else {
if (context.log.length > page_size && context.flushable) {
context.flushable = false;
Fs.appendFile(pathname(temp_filename), context.log.substr(), function() {
return context.flushable = true;
});
return context.log = '';
}
}
});
buffer.on('unpipe', function() {
var wait_io;
wait_io = function() {
if (context.flushable) {
return Fs.appendFile(pathname(temp_filename), context.log, function() {
return callback();
});
} else {
return setTimeout(wait_io, 10);
}
};
return wait_io();
});
readStream = Fs.createReadStream(pathname());
return readStream.on('open', function() {
return readStream.pipe(buffer);
});
};
context = {
log: '',
flushable: true
};
copy(context, function() {
return clear(function() {
var compacting_db;
compacting_db = require_db(temp_filename);
return Fs.unlink(pathname(temp_filename), function() {
var wait_io, writer;
context = {
log: '',
flushable: true
};
writer = function(chunk, index) {
var ref1;
context.log += (ref1 = (index > 0 ? ',' : '') + chunk) != null ? ref1 : '';
if (context.flushable && (context.log.length > page_size || (chunk == null))) {
context.flushable = false;
Fs.appendFile(pathname(temp_filename), context.log.substr(), function() {
return context.flushable = true;
});
context.log = "";
}
};
compacting_db._op_index = null;
stringify(compacting_db, {
write: writer,
strict: true,
variable: true
});
wait_io = function() {
if (context.flushable) {
context.log += (init('', {
var_str: '',
alias: true,
rebuild: true
})) + "\n";
return Fs.appendFile(pathname(temp_filename), context.log, function() {
context = {
log: '',
flushable: true
};
return copy(context, {
append: true
}, function() {
return Fs.unlink(pathname(), function() {
return Fs.rename(pathname(temp_filename), pathname(), function() {
load();
return typeof callback === "function" ? callback() : void 0;
});
});
});
});
} else {
return setTimeout(wait_io, 10);
}
};
return wait_io();
});
});
});
}
};
flushed = function(callback) {
if (_queue.length > 0) {
return _flushed.push(callback);
} else {
return setTimeout((function() {
return typeof callback === "function" ? callback() : void 0;
}), 10);
}
};
return {
load: load,
loaded: loaded,
io: io,
write: write,
update: update,
flushed: flushed,
register: register,
upgrade: upgrade,
module: module_,
clear: clear,
revert: revert,
compact: compact,
filename: filename,
pathname: pathname
};
};
Log.exists = function(name, datadir, callback) {
var Fs, ref;
if (typeof datadir === 'function') {
callback = datadir;
datadir = null;
}
if ((ref = typeof name) === 'function' || ref === 'undefined') {
callback = name;
name = _defaults.filename;
}
if (datadir == null) {
datadir = _defaults.datadir;
}
if (typeof window !== "undefined" && window !== null) {
setTimeout((function() {
return typeof callback === "function" ? callback(localStorage.getItem('LateDB-' + name) != null) : void 0;
}), 10);
} else {
Fs = require('fs');
Fs.exists(datadir + '/' + name, function(exists) {
return typeof callback === "function" ? callback(exists) : void 0;
});
}
};
lateDB = function(name, path) {
var db, log;
if (name != null) {
if (path == null) {
path = typeof process !== "undefined" && process !== null ? process.cwd() : void 0;
}
}
if (name == null) {
name = _defaults.filename;
}
db = loadedDBs[name];
if ((db != null) && !db.loaded()) {
db.load();
if (db.tables.count() > 0) {
db.tables.init();
}
}
if (db != null) {
return db;
}
log = Log();
if (name !== _defaults.filename) {
log.filename(name);
}
if (path != null) {
log.pathname(name, path);
}
log.load();
db = function(path, data, op) {
return log.io.apply(log, arguments);
};
db.flushed = function(callback) {
return log.flushed.apply(log, arguments);
};
db.revert = function(time, callback) {
return log.revert.apply(log, arguments);
};
db.compact = function(time, callback) {
return log.compact.apply(log, arguments);
};
db.register = function(name, service) {
return log.register.apply(log, arguments);
};
db.module = function(name) {
return log.module.apply(log, arguments);
};
db.clear = function(options, callback) {
return log.clear.apply(log, arguments);
};
db.pathname = function(options, callback) {
return log.pathname.apply(log, arguments);
};
db.update = function(updates) {
return log.update.apply(log, arguments);
};
db.filename = function(name) {
return log.filename.apply(log, arguments);
};
db.load = function() {
return log.load.apply(log, arguments);
};
db.loaded = function() {
return log.loaded.apply(log, arguments);
};
db.world = (function() {
var delete_, get_world, insert, select, update;
get_world = function() {
return log.module('World');
};
select = function(query) {
var World, self, uuid;
if ((World = get_world()) == null) {
return;
}
path = query.path, uuid = query.uuid;
if (typeof query === 'string') {
uuid = query;
}
if (path != null) {
self = db(path);
if (self == null) {
return;
}
if (uuid != null) {
return self[uuid];
} else {
return self;
}
} else {
return World[uuid];
}
};
insert = function(path, uuid, object) {
if (!((path != null) && (uuid != null))) {
return;
}
if (get_world() == null) {
log.register('World', {});
}
return db(path, {
uuid: uuid,
object: object
}, function(o, arg) {
var World, k, name1, ref, self, v;
World = arg.World;
self = this[name1 = o.uuid] != null ? this[name1] : this[name1] = {};
ref = o.object;
for (k in ref) {
v = ref[k];
self[k] = v;
}
World[o.uuid] = self;
});
};
update = function(path, uuid, object) {
if (!((get_world() != null) && (path != null) && (uuid != null) && (object != null))) {
return;
}
return db(path, {
uuid: uuid,
object: object
}, function(o, arg) {
var World, k, ref, self, v;
World = arg.World;
self = World[o.uuid];
ref = o.object;
for (k in ref) {
v = ref[k];
self[k] = v;
}
});
};
delete_ = function(path, uuid) {
if (!((get_world() != null) && (path != null) && (uuid != null))) {
return;
}
return db(path, {
uuid: uuid
}, function(o, arg) {
var World;
World = arg.World;
delete World[o.uuid];
delete this[o.uuid];
});
};
return {
select: select,
insert: insert,
update: update,
"delete": delete_
};
})();
db.tables = (function() {
var Field, History, Index, IndexTable, Iterator, List, QueryIterator, Table, TransientTable, _helpers, _query_defs, alter, clone, count, create, delete_, diff_update, drop, entity, exists, extend, get, id, init, insert, list, query, update;
Table = function() {
return {
lines: {},
length: 0
};
};
Table.insert = function(table, line) {
var inc;
if (line.id == null) {
return;
}
inc = table.lines[line.id] != null ? 0 : 1;
table.lines[line.id] = line;
table.length += inc;
return Table.notify(table, 'insert', line);
};
Table.patchLine = function(line, patch, do_prune) {
var has_one, k, kk, pruned, ref, v;
if (do_prune == null) {
do_prune = false;
}
pruned = false;
for (k in patch) {
v = patch[k];
if ((v != null) && ((ref = v.constructor) === Object || ref === Array) && (line[k] != null)) {
if ((pruned = Table.patchLine(line[k], v, do_prune))) {
has_one = false;
for (kk in line[k]) {
has_one = true;
break;
}
if (!has_one) {
delete line[k];
}
}
} else {
if (!do_prune) {
line[k] = v;
} else if (v === true) {
delete line[k];
pruned = true;
if (line.constructor === Array && (line[line.length - 1] == null)) {
line.pop();
}
}
}
}
return pruned;
};
Table.update = function(table, update, prune) {
var line, ref;
if (!(((update != null ? update.id : void 0) != null) || ((prune != null ? prune.id : void 0) != null))) {
return;
}
line = table.lines[(ref = update != null ? update.id : void 0) != null ? ref : prune != null ? prune.id : void 0];
if (line == null) {
return;
}
Table.patchLine(line, update);
if (prune != null) {
Table.patchLine(line, prune, true);
}
return Table.notify(table, 'update', update);
};
Table["delete"] = function(table, line) {
var dec, ref, ref1;
if (!(((line != null ? line.id : void 0) != null) || (line != null))) {
return;
}
dec = table.lines[(ref = line.id) != null ? ref : line] != null ? 1 : 0;
delete table.lines[(ref1 = line.id) != null ? ref1 : line];
table.length -= dec;
return Table.notify(table, 'delete', line);
};
Table.notify = function(table, event, line) {
var j, len, observer, observers, ref, results;
if ((observers = (ref = table.observers) != null ? ref[event] : void 0) != null) {
results = [];
for (j = 0, len = observers.length; j < len; j++) {
observer = observers[j];
results.push(observer(table, line));
}
return results;
}
};
Table.observe = function(table, event, observer) {
var base, observers;
if (table.observers == null) {
table.observers = {};
}
observers = (base = table.observers)[event] != null ? base[event] : base[event] = [];
return observers.push(observer);
};
Table.toArray = function(table) {
var arr, id, line, ref;
arr = [];
ref = table.lines;
for (id in ref) {
line = ref[id];
arr.push(line);
}
return arr;
};
if ((log.module('Table')) != null) {
log.upgrade('Table', Table);
}
List = function() {
return {
items: {},
first: null,
last: null
};
};
List.upgrade = function(table) {
var id, line, ref;
if (table.list == null) {
table.list = List();
ref = table.lines;
for (id in ref) {
line = ref[id];
List.insert(table, line);
}
Table.observe(table, 'insert', List.insert);
Table.observe(table, 'delete', List["delete"]);
}
return table;
};
List.insert = function(table, line) {
var item, list, ref;
list = table.list;
item = (ref = list.last) != null ? ref : {
line: null,
previous: null,
next: null
};
if (list.first == null) {
item.line = line;
list.first = item;
} else {
item.next = item = {
line: line,
previous: item,
next: null
};
}
list.last = item;
list.items[line.id] = item;
return item;
};
List["delete"] = function(table, line) {
var deleted, list, next, previous;
list = table.list;
deleted = list.items[line.id];
delete list.items[line.id];
previous = deleted.previous, next = deleted.next;
if (previous != null) {
previous.next = next;
}
if (next != null) {
next.previous = previous;
}
if (deleted === list.first) {
list.first = next;
}
if (deleted === list.last) {
list.last = previous;
}
return deleted;
};
TransientTable = function(table) {
return table != null ? table : [];
};
TransientTable.insert = function(table, line) {
return table.push(line);
};
TransientTable.fromTable = function(table, filter) {
var id, j, len, line, ref, ref1, t_table;
t_table = [];
if (table.lines != null) {
if (filter != null) {
ref = table.lines;
for (id in ref) {
line = ref[id];
if (filter(line)) {
t_table.push(line);
}
}
} else {
ref1 = table.lines;
for (id in ref1) {
line = ref1[id];
t_table.push(line);
}
}
} else {
if (filter != null) {
for (j = 0, len = table.length; j < len; j++) {
line = table[j];
if (filter(line)) {
t_table.push(line);
}
}
} else {
t_table = table.slice();
}
}
return t_table;
};
IndexTable = function() {
var table;
table = Table();
table.list = List();
return table;
};
IndexTable.insert = function(table, line) {
var ref;
table.lines[(ref = line.id) != null ? ref : table.length] = line;
table.length++;
List.insert(table, line);
};
IndexTable["delete"] = function(table, line) {
var id, one_line, ref;
if (line.id != null) {
delete table.lines[line.id];
} else {
ref = table.lines;
for (id in ref) {
one_line = ref[id];
if (one_line === line) {
delete table.lines[id];
break;
}
}
}
table.length--;
List["delete"](table, line);
};
Iterator = function(table) {
return {
current: null,
index: 0,
has_next: function() {
if (table.lines != null) {
if (this.current != null) {
return this.current.next != null;
} else {
return table.list.first != null;
}
} else {
return table[this.index + 1];
}
},
next: function() {
var ref;
if (table.lines != null) {
this.index++;
this.current = this.current != null ? this.current.next : table.list.first;
return (ref = this.current) != null ? ref.line : void 0;
} else {
return this.current = table[this.index++];
}
}
};
};
Field = {};
Field.insert_from_line = function(table, line) {
var k, ref, v;
for (k in line) {
v = line[k];
if (!((ref = table.fields) != null ? ref[k] : void 0)) {
alter(table.name, {
add: k
});
}
}
};
Index = {};
Index.create = function(table, fields_only) {
var id, line, ref, ref1;
if (table.index == null) {
ref = table.lines;
for (id in ref) {
line = ref[id];
Index.create_line_fields_index(table, line);
}
}
if (fields_only !== true) {
ref1 = table.lines;
for (id in ref1) {
line = ref1[id];
Index.create_line_cross_refs(table, line);
}
}
};
Index.create_line_fields_index = function(table, line) {
var base, base1, base2, field, index_table, ref, value;
if (table.index == null) {
table.index = {};
}
if ((base = table.index).id == null) {
base.id = {};
}
for (field in line) {
value = line[field];
if ((field === 'id' || field === 'idx') || ((ref = field.slice(-3)) === '_id' || ref === 'Idx')) {
if (field !== 'id') {
if ((base1 = table.index)[field] == null) {
base1[field] = {};
}
index_table = (base2 = table.index[field])[value] != null ? base2[value] : base2[value] = IndexTable();
IndexTable.insert(index_table, line);
} else {
table.index.id[value] = line;
}
}
}
};
Index.delete_line_fields_index = function(table, line) {
var field, index_table, ref, ref1, ref2, value;
if (table.index == null) {
return;
}
for (field in line) {
value = line[field];
if ((field === 'id' || field === 'idx') || ((ref = field.slice(-3)) === '_id' || ref === 'Idx')) {
if (field !== 'id') {
index_table = (ref1 = table.index[field]) != null ? ref1[value] : void 0;
if (index_table != null) {
IndexTable["delete"](index_table, line);
}
} else {
if ((ref2 = table.index.id) != null) {
delete ref2[value];
}
}
}
}
};
Index.create_line_cross_refs = function(table, line) {
var base, base1, entities, field, index_in_joined_table, joined_line, joined_line_join_table, joined_table, joined_table_name, k, linked_entity_name, name1, ref, tables, v, value;
tables = db('tables');
entities = db('entities');
for (field in line) {
value = line[field];
if (field.slice(-3) === '_id') {
linked_entity_name = field.slice(0, -3).toLowerCase();
joined_table_name = entities[linked_entity_name];
if ((joined_table = tables[joined_table_name]) != null) {
if (joined_table.index == null) {
Index.create(joined_table, true);
}
if ((joined_line = joined_table.index.id[value]) != null) {
joined_line_join_table = joined_line[name1 = table.name + '_joins'] != null ? joined_line[name1] : joined_line[name1] = IndexTable();
IndexTable.insert(joined_line_join_table, line);
if (joined_line_join_table.index == null) {
joined_line_join_table.index = {};
}
for (k in line) {
v = line[k];
if (!((k === 'id' || k === 'idx') || ((ref = k.slice(-3)) === '_id' || ref === 'Idx'))) {
continue;
}
if ((base = joined_line_join_table.index)[k] == null) {
base[k] = {};
}
index_in_joined_table = (base1 = joined_line_join_table.index[k])[v] != null ? base1[v] : base1[v] = IndexTable();
IndexTable.insert(index_in_joined_table, line);
}
line[joined_table_name + '_ref'] = joined_line;
}
}
}
}
};
Index.delete_line_cross_refs = function(table, line) {
var entities, field, index_in_joined_table, joined_line, joined_line_join_table, joined_table, joined_table_name, k, linked_entity_name, ref, tables, v, value;
tables = db('tables');
entities = db('entities');
for (field in line) {
value = line[field];
if (field.slice(-3) === '_id') {
linked_entity_name = field.slice(0, -3).toLowerCase();
joined_table_name = entities[linked_entity_name];
if ((joined_table = tables[joined_table_name]) != null) {
if (joined_table.index == null) {
continue;
}
joined_line = joined_table.index.id[value];
joined_line_join_table = joined_line[table.name + '_joins'];
if (joined_line_join_table) {
IndexTable["delete"](joined_line_join_table, line);
}
if (joined_line_join_table.index == null) {
continue;
}
for (k in line) {
v = line[k];
if (!((k === 'id' || k === 'idx') || ((ref = k.slice(-3)) === '_id' || ref === 'Idx'))) {
continue;
}
if (joined_line_join_table.in