-
Notifications
You must be signed in to change notification settings - Fork 0
/
cantina.js
290 lines (244 loc) · 6.65 KB
/
cantina.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Modules dependencies.
var EventEmitter = require('events').EventEmitter
, inherits = require('util').inherits
, etc = require('etc')
, etcYaml = require('etc-yaml')
, witwip = require('witwip')
, path = require('path')
, fs = require('fs')
, resolve = require('resolve')
, glob = require('glob')
, _ = require('underscore')
, callerId = require('caller-id')
, createHooks = require('stact-hooks');
/**
* Application constructor.
*/
function Cantina (options) {
EventEmitter.call(this);
var app = this;
options = options || {};
// Set max listeners.
app.setMaxListeners(0);
// Create a hooks stack.
app.hook = createHooks();
// Expose basic logging.
app.log = console.log;
app.log.error = console.error;
app.log.info = console.log;
app.log.warn = console.warn;
// Cached plugins.
app._plugins = {};
// Loaders registry.
app._loaders = {};
/**
* Register a 'modules' type loader. Loads .js files in the target directory
* OR index.js files in nested directories. Returns the required modules.
* Respects `module.exports.weight` for each module.
*/
app.loader('modules', function (options) {
var app = this
, modules = [];
// Find files in the directory.
glob.sync(options.path + '/*.js').forEach(function (p) {
modules.push({
name: path.basename(p, '.js'),
path: path.resolve(p),
weight: require(path.resolve(p)).weight || 0
});
});
// Find index.js files one level down.
glob.sync(options.path + '/*/index.js').forEach(function (p) {
modules.push({
name: path.dirname(p).split('/').pop(),
path: path.resolve(p),
weight: require(path.resolve(p)).weight || 0
});
});
// Sort by weight.
modules.sort(function (a, b) {
return a.weight - b.weight;
});
// Load all modules.
return modules.reduce(function (hash, module) {
hash[module.name] = app.require(module.path);
if (hash[module.name] && (typeof hash[module.name].weight === 'undefined')) {
hash[module.name].weight = module.weight;
}
return hash;
}, {});
});
/**
* Registers a plugins loader.
*/
app.loader('plugins', function (options) {
return this.load('modules', options);
});
/**
* Register a configuration loader.
*/
app.loader('conf', function (options) {
if (fs.existsSync(path.join(options.parent, 'etc'))) {
this.conf.etc(path.join(options.parent, 'etc'));
}
if (fs.existsSync(path.join(options.parent, 'package.json'))) {
this.conf.pkg(path.join(options.parent, 'package.json'));
}
});
}
inherits(Cantina, EventEmitter);
/**
* Boot the application.
*/
Cantina.prototype.boot = function (root, callback) {
var app = this;
app.conf = etc().use(etcYaml).argv().env();
if (typeof root === 'function') {
callback = root;
root = null;
}
function setup (err, pkgPath, pkgData) {
if (err) return callback(err);
// Set pkg and root paths.
if (pkgPath) {
app.pkgPath = pkgPath;
app.pkgData = pkgData;
app.root = path.dirname(pkgPath);
}
else {
app.root = root;
}
// Add ./etc of parent.
app.conf.folder(path.join(app.root, 'etc'));
// Add package.json of the app.
if (app.pkgPath) {
app.conf.pkg(app.pkgPath);
}
callback();
}
if (root) {
witwip(root, setup);
}
else {
witwip(path.dirname(module.parent.filename), setup);
}
};
/**
* Start the application.
*/
Cantina.prototype.start = function (callback) {
var app = this;
callback = callback || function startCallback (err) {
if (!err) return;
app.emit('error', err);
};
// Run 'start' and 'started' hooks.
app.hook('start').runSeries(function (err) {
if (err) return callback(err);
app.hook('started').run(callback);
});
};
/**
* Destroy the app.
*/
Cantina.prototype.destroy = function (callback) {
var app = this;
// Run 'destroy' hooks.
app.hook('destroy').runSeries(function (err) {
if (err) return callback(err);
// Clear the require cache.
Object.keys(require.cache).forEach(function (key) {
delete require.cache[key];
});
// Clear the plugin cache.
app._plugins = {};
callback();
});
};
/**
* 'Silence' the app.
*/
Cantina.prototype.silence = function () {
var app = this;
var noops = Object.keys(app.log).filter(function (prop) {
return typeof app.log[prop] === 'function';
});
app.log = function () {};
noops.forEach(function (noop) {
app.log[noop] = app.log;
});
};
/**
* Load a plugin (cached).
*/
Cantina.prototype.require = function () {
var app = this
, base = path.dirname(callerId.getData().filePath)
, args = Array.prototype.slice.call(arguments, 0)
, results = [];
args.forEach(function (arg) {
var resolved = resolve.sync(arg, {basedir: base})
, plugin;
if (typeof app._plugins[resolved] === 'undefined') {
app._plugins[resolved] = {}
app._plugins[resolved].result = 'APP_REQUIRE_CIRCULAR_DEP_PLACEHOLDER';
app._plugins[resolved].plugin = require(resolved);
if (typeof app._plugins[resolved].plugin !== 'function') {
throw new Error('Export of `' + resolved + '` is not a cantina plugin');
}
app._plugins[resolved].result = app._plugins[resolved].plugin(app);
}
results.push(app._plugins[resolved].result);
});
if (args.length > 1) {
return results;
}
else {
return results.shift();
}
};
/**
* Register a loader.
*/
Cantina.prototype.loader = function (type, defaults, handler) {
var app = this;
if (typeof handler !== 'function') {
handler = defaults;
defaults = {};
}
_.defaults(defaults, {
dir: type
});
app._loaders[type] = {
defaults: defaults,
handler: handler
};
};
/**
* Run a loader.
*
* Options:
* - parent: The root directory where the target directory is found. Defaults
* to the calling function's directory.
* - dir: The name of the directory we are loading. Defaults to type.
*/
Cantina.prototype.load = function (type, options) {
var app = this;
if (!app._loaders[type]) throw new Error('Tried to load an unregistered type: ' + type);
// Apply options, loader defaults, and invocation defaults.
options = _.defaults({}, options, app._loaders[type].defaults, {
parent: path.dirname(callerId.getData().filePath)
});
// Set the path.
options.path = path.resolve(options.parent, options.dir);
// Call the loader handler.
return app._loaders[type].handler.call(this, options);
};
/**
* Exports.
*/
module.exports = Cantina;
module.exports.createApp = function (options) {
return new Cantina(options);
};
module.exports.etc = etc;