-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
356 lines (272 loc) · 8.65 KB
/
index.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/**
* Native components
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.start = start;
exports.use = use;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
/**
* Module Dependencies
*/
var _bodyParser = require('body-parser');
var _bodyParser2 = _interopRequireDefault(_bodyParser);
var _compression = require('compression');
var _compression2 = _interopRequireDefault(_compression);
var _cookieParser = require('cookie-parser');
var _cookieParser2 = _interopRequireDefault(_cookieParser);
var _debug = require('debug');
var _debug2 = _interopRequireDefault(_debug);
var _express = require('express');
var _express2 = _interopRequireDefault(_express);
var _expressSession = require('express-session');
var _expressSession2 = _interopRequireDefault(_expressSession);
var _featureClient = require('feature-client');
var _featureClient2 = _interopRequireDefault(_featureClient);
var _glob = require('glob');
var _glob2 = _interopRequireDefault(_glob);
var _methodOverride = require('method-override');
var _methodOverride2 = _interopRequireDefault(_methodOverride);
var _morgan = require('morgan');
var _morgan2 = _interopRequireDefault(_morgan);
var _bluebird = require('bluebird');
var _bluebird2 = _interopRequireDefault(_bluebird);
var _xprExpress = require('xpr-express');
var _xprExpress2 = _interopRequireDefault(_xprExpress);
var _xprToggle = require('xpr-toggle');
var _xprToggle2 = _interopRequireDefault(_xprToggle);
/**
* Local Dependencies
*/
/**
* Local Constants
*/
var app = (0, _express2['default'])();
var debug = (0, _debug2['default'])('jack-stack');
var routerMatch = (0, _express.Router)();
/**
* This config object will be overridable during the `config` event
*/
var config = {
cookie: {
secret: 'You put the lime in the coconut'
},
session: {
name: 'sessionID',
secret: 'What would the fox say if he knew...?',
getStore: function getStore() {
console.warn('\n\n\nExpress MemoryStore should not be used in production...\n\n\n');
}
},
experiments: ['placeholderExperiment'],
bodyParser: {
urlencoded: {
extended: false
}
},
morgan: 'dev',
dirnames: {
'static': [_path2['default'].join(process.cwd(), 'public')],
routes: [_path2['default'].join(process.cwd(), 'routes')]
},
port: 5000,
assign: function assign(newConfig) {
Object.assign(config, newConfig);
}
};
/**
* Used to validate if experiments are enabled or not
*/
var delays = [];
/**
* Used to validate if experiments are enabled or not
*/
var experimented = false;
/**
* Used to make sure the express app is initialized before starting
*/
var initialized = false;
/**
* Used for event short-names
*/
var registeredEvents = [];
/**
* Used to log the initialization order of middleware, etc
*/
var initOrder = 1;
function wrap(name, fn) {
registeredEvents.push(name);
var eventData = {
app: app,
config: config,
registerDelay: registerDelay
};
app.emit('before.' + name, eventData);
app.emit('before.init.' + name, registerDelay);
console.log(initOrder++ + ': ' + name);
if (fn) fn();
app.emit('after.init.' + name, registerDelay);
app.emit('after.' + name, eventData);
function registerDelay(promise) {
if (typeof promise.next !== 'function') return;
delays.push(promise);
}
}
function init() {
initialized = true;
app.emit('config', config);
wrap('config');
// Req.cookie
wrap('cookie', function () {
debug('cookie');
app.use((0, _cookieParser2['default'])(config.cookie.secret));
});
// Req.user
wrap('session', function () {
debug('session');
var store = config.session.getStore(_expressSession2['default']);
config.session.store = store;
var sessionConfig = {
key: config.session.name,
secret: config.session.secret,
resave: false,
saveUninitialized: false
};
if (store) sessionConfig.store = store;
app.use((0, _expressSession2['default'])(sessionConfig));
});
// Load static assets
wrap('static', function () {
debug('static');
var dirs = config.dirnames['static'];
if (!Array.isArray(dirs)) dirs = [dirs];
dirs.map(function (dir) {
app.use(_express2['default']['static'](dir));
});
});
// Log everything after this
wrap('logging', function () {
debug('logging');
app.use((0, _morgan2['default'])(config.morgan));
});
// Req.feature
wrap('xprmntl', function () {
debug('xprmntl');
var xprConfig = config.experiments;
experimented = !!xprConfig;
if (!experimented) return;
if (Array.isArray(xprConfig)) xprConfig = { experiments: xprConfig };
_featureClient2['default'].use((0, _xprExpress2['default'])());
_featureClient2['default'].use((0, _xprToggle2['default'])());
_featureClient2['default'].configure(xprConfig);
app.use(_featureClient2['default'].express);
app.use(_featureClient2['default'].toggle);
if (xprConfig.cron) _featureClient2['default'].cron(xprConfig.cron);
delays.push(_featureClient2['default'].announce()['catch'](function () {
// If there's no XPRMNTL Dashboard response,
// I want to start the app anyway, just with the fallbacks
return _bluebird2['default'].resolve();
}));
});
// Parse application/json
wrap('json', function () {
debug('json');
app.use(_bodyParser2['default'].json(config.bodyParser.json));
});
// Parse application/x-www-form-urlencoded
wrap('urlencoded', function () {
debug('urlencoded');
app.use(_bodyParser2['default'].urlencoded(config.bodyParser.urlencoded));
});
// Fake PUT and DELETE when clients don't support
wrap('override', function () {
debug('override');
app.use((0, _methodOverride2['default'])(config.methodOverride));
});
// GZip all of our responses
wrap('compress', function () {
debug('compress');
app.use((0, _compression2['default'])(config.compression));
});
// Any routing level stuff
wrap('routing', function () {
debug('routing');
var dirs = config.dirnames.routes;
if (!Array.isArray(dirs)) dirs = [dirs];
// Dir order matters
dirs.forEach(function (dir) {
var dirFiles = {};
_glob2['default'].sync(_path2['default'].join(dir, '**', '*.js')).forEach(function (filename) {
var route = filename.replace(dir, '') // Get just the file
.replace(/\.js$/, '') // Basename
.replace(/index$/, ''); // And use index as './'
dirFiles[route] = filename;
});
// Sort by the path, since '/' needs to come first
Object.keys(dirFiles).sort().forEach(function (route) {
var filename = dirFiles[route];
debug(route, filename);
var file = require(filename);
if (file instanceof routerMatch.constructor) return app.use(route, file);
var instance = require(file);
if (typeof instance === 'function' && instance.length === 2) return instance(app);
console.error('\n\n\nFile incompatible and not loaded: ' + file + '\n\n\n');
});
});
debug('routing done');
});
}
function start(cb) {
if (!initialized) init();
return _bluebird2['default'].all(delays).then(appListen.bind(app, config.port)).then(function () {
if (cb) cb();
})['catch'](function (err) {
console.error(err);
if (cb) cb(err);
throw err;
});
function appListen(port) {
return new _bluebird2['default'](function (resolve) {
if (config.sockets && config.sockets.server) {
return config.sockets.server.listen(port, function () {
return resolve();
});
}
app.listen(port, function () {
return resolve();
});
});
}
}
var useBefore = app.useBefore = useAround('before.');
var useAfter = app.useAfter = useAround('after.');
function useAround(prefix) {
return function (method, name, handler) {
var eventName = prefix + method;
if (typeof name === 'function') throw new Error('No name provided: useAround(\'' + eventName + '\')');
app.on('' + eventName, function (data) {
wrap(name, function () {
handler(data);
});
});
};
}
function use(modules) {
if (!Array.isArray(modules)) modules = [modules];
modules.map(function (module) {
app.on(module.event, module.handler);
});
}
exports['default'] = { app: app, start: start, init: init, wrap: wrap, use: use, useAfter: useAfter, useBefore: useBefore, Router: _express.Router };
exports.init = init;
exports.start = start;
exports.wrap = wrap;
exports.app = app;
exports.use = use;
exports.useAfter = useAfter;
exports.useBefore = useBefore;
exports.Router = _express.Router;