lien 3.4.4 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1119 +1,20 @@
1
- "use strict";
2
-
3
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
4
-
5
- var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6
-
7
- function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
8
-
9
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
10
-
11
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12
-
13
- var events = require("events"),
14
- EventEmitter = events.EventEmitter,
15
- express = require("express"),
16
- bodyParser = require("body-parser"),
17
- ul = require("ul"),
18
- http = require("http"),
19
- https = require("https"),
20
- fs = require("fs"),
21
- path = require("path"),
22
- toBuffer = require("./to-buffer"),
23
- session = require("express-session"),
24
- findValue = require("find-value"),
25
- qs = require("querystring"),
26
- Transformer = require("transformer"),
27
- setOrGet = require("set-or-get"),
28
- httpMethods = require("methods"),
29
- _require = require("path-to-regexp"),
30
- pathToRegexp = _require.pathToRegexp,
31
- iterateObject = require("iterate-object"),
32
- noop = require("noop6"),
33
- cookieParser = require("cookie-parser"),
34
- csrf = require("csurf");
35
-
36
- var LienObj = function () {
37
-
38
- /**
39
- * LienCreator
40
- * Creates the `lien` object.
41
- *
42
- * @name LienCreator
43
- * @function
44
- * @param {Object} req The request object.
45
- * @param {Object} res The response object.
46
- * @param {Function} next The `next` middleware function.
47
- * @param {Object} server The `Lien` server instance.
48
- * @return {Lien} The lien object.
49
- */
50
- function LienObj(req, res, next, server) {
51
- var _this = this;
52
-
53
- _classCallCheck(this, LienObj);
54
-
55
- this._next = next;
56
- this.req = req;
57
- this.res = res;
58
-
59
- this.path = this.req.path;
60
-
61
- if (this.path.charAt(this.path.length - 1) === "/") {
62
- this.path = this.path.slice(0, -1) || "/";
63
- }
64
-
65
- this.accepts = req.accepts.bind(req);
66
- this.host = req.hostname;
67
- this.params = req.params;
68
- this.query = req.query;
69
- this.pathname = req.baseUrl + req.path;
70
- this.method = req.method.toLowerCase();
71
- this.cookies = req.cookies || {};
72
- this.server = server;
73
- this.data = req.body;
74
- this.session = req.session;
75
- Object.defineProperty(this, "csrfToken", {
76
- get: function get() {
77
- return _this.req.csrfToken && _this.req.csrfToken() || "";
78
- }
79
- });
80
- Object.defineProperty(this, "csrfInput", {
81
- get: function get() {
82
- return _this.req.csrfToken ? "<input type=\"hidden\" name=\"_csrf\" value=\"" + _this.req.csrfToken() + "\">" : "";
83
- }
84
- });
85
-
86
- this.full_path = req.originalUrl;
87
- this.protocol = req.protocol;
88
- this.domain = this.protocol + "://" + this.host + (this.host === "localhost" ? ":" + server.options.port : "");
89
- this.href = "" + this.domain + req.originalUrl;
90
- }
91
-
92
- /**
93
- * next
94
- * Go to the next middleware handler.
95
- *
96
- * @name next
97
- * @function
98
- * @returns {Lien} The `Lien` instance.
99
- */
100
-
101
-
102
- _createClass(LienObj, [{
103
- key: "next",
104
- value: function next(err, data) {
105
- this._next(err, data);
106
- return this;
107
- }
108
-
109
- /**
110
- * redirect
111
- * Redirects the client to another url.
112
- *
113
- * @name redirect
114
- * @function
115
- * @param {String} newUrl The new url to redirect to.
116
- * @param {Boolean|Object} query If `true`, the request querystring parameters will be appended. If it's an object, it will be merged with the request querystring parameters.
117
- */
118
-
119
- }, {
120
- key: "redirect",
121
- value: function redirect(newUrl, query) {
122
- if (query) {
123
- var sQuery = null;
124
- sQuery = qs.stringify(query === true ? this.query : ul.merge(query, this.query));
125
- sQuery && (newUrl += "?" + sQuery);
126
- }
127
- this.res.redirect(newUrl);
128
- }
129
-
130
- /**
131
- * render
132
- * Renders a template to the client.
133
- *
134
- * @name render
135
- * @function
136
- * @param {String} template The template name.
137
- * @param {Object} data The template data.
138
- */
139
-
140
- }, {
141
- key: "render",
142
- value: function render(template, data) {
143
- this.res.render(template, data);
144
- }
145
-
146
- /*!
147
- * _checkSessionSupport
148
- * Checks if the session is supported or not.
149
- *
150
- * @name _checkSessionSupport
151
- * @function
152
- * @returns {Boolean} `false` if session is *not* supported. `true` otherwise.
153
- */
154
-
155
- }, {
156
- key: "_checkSessionSupport",
157
- value: function _checkSessionSupport() {
158
- if (this.session) {
159
- return true;
160
- }
161
- console.warn("You're trying to use a session feature, but you didn't enable the session support.");
162
- return false;
163
- }
164
-
165
- /**
166
- * startSession
167
- * Starts a session.
168
- *
169
- * @name startSession
170
- * @function
171
- * @param {Object} data The session data.
172
- */
173
-
174
- }, {
175
- key: "startSession",
176
- value: function startSession(data) {
177
- if (!this._checkSessionSupport()) {
178
- return;
179
- }
180
- this.setSessionData(data);
181
- }
182
-
183
- /**
184
- * setSessionData
185
- * Sets the session data.
186
- *
187
- * @name setSessionData
188
- * @function
189
- * @param {Object} data The session data.
190
- */
191
-
192
- }, {
193
- key: "setSessionData",
194
- value: function setSessionData(data) {
195
- if (!this._checkSessionSupport()) {
196
- return;
197
- }
198
- this.session._sessionData = ul.deepMerge(data, this.getSessionData());
199
- }
200
-
201
- /**
202
- * getSessionData
203
- * Returns the session data object/specific field.
204
- *
205
- * @name getSessionData
206
- * @function
207
- * @param {Field} field A specific field to get from the session object.
208
- * @returns {Value|Object} The field value. If a field is not specified,
209
- * the whole session data object is returned.
210
- */
211
-
212
- }, {
213
- key: "getSessionData",
214
- value: function getSessionData(field) {
215
- if (!this._checkSessionSupport()) {
216
- return;
217
- }
218
- if (field) {
219
- return findValue(this.session._sessionData, field) || null;
220
- }
221
- return this.session._sessionData;
222
- }
223
-
224
- /**
225
- * destroySession
226
- * Destroys the session.
227
- *
228
- * @name destroySession
229
- * @function
230
- */
231
-
232
- }, {
233
- key: "destroySession",
234
- value: function destroySession() {
235
- if (!this._checkSessionSupport()) {
236
- return;
237
- }
238
- this.session.destroy();
239
- }
240
-
241
- /**
242
- * header
243
- * Gets/sets/deletes headers.
244
- *
245
- * @name header
246
- * @function
247
- * @param {String} name The header name.
248
- * @param {String} value The header value to set. If `null`, the header will be *removed*.
249
- * @returns {Lien} The Lien instance.
250
- */
251
-
252
- }, {
253
- key: "header",
254
- value: function header(name, value) {
255
-
256
- if (!name && !value) {
257
- return this.req.headers;
258
- }
259
-
260
- if (value === null) {
261
- return this.res.removeHeader(name);
262
- }
263
-
264
- if (value === undefined && typeof name === "string") {
265
- return this.req.header(name);
266
- }
267
-
268
- if ((typeof name === "undefined" ? "undefined" : _typeof(name)) === "object") {
269
- this.res.set(name);
270
- } else {
271
- this.res.set(name, value);
272
- }
273
-
274
- return this;
275
- }
276
-
277
- /**
278
- * apiMsg
279
- * Sends to the client a JSON object containing the `message` field.
280
- *
281
- * @name apiMsg
282
- * @function
283
- * @param {String} msg The API message.
284
- * @param {Number} status The status code (default: `200`).
285
- */
286
-
287
- }, {
288
- key: "apiMsg",
289
- value: function apiMsg(msg, status) {
290
- status = status || 200;
291
- this.end({ message: msg }, status);
292
- }
293
-
294
- /**
295
- * apiError
296
- * Like `apiMsg`, but by default with a status code of `422`.
297
- *
298
- * @name apiError
299
- * @function
300
- * @param {String} msg The API message.
301
- * @param {Number} status The status code (default: `422`).
302
- */
303
-
304
- }, {
305
- key: "apiError",
306
- value: function apiError(msg, status) {
307
- msg = msg.message || msg;
308
- this.apiMsg(msg, status || 422);
309
- }
310
-
311
- /**
312
- * end
313
- * Ends the response sending the content.
314
- *
315
- * @name end
316
- * @function
317
- * @param {Anything} content The content that should be sent to the response.
318
- * @param {Number} status The status code.
319
- * @param {String} contentType The content type (e.g. `"json"`).
320
- * @param {Object} headers Additional headers to send in the response.
321
- */
322
-
323
- }, {
324
- key: "end",
325
- value: function end(content, status, contentType, headers) {
326
- var _this2 = this;
327
-
328
- var resData = {};
329
-
330
- // end(content, status, headers)
331
- if ((typeof contentType === "undefined" ? "undefined" : _typeof(contentType)) === "object") {
332
- headers = contentType;
333
- contentType = null;
334
- }
335
-
336
- // end(status, headers)
337
- if (typeof content === "number") {
338
- status = content;
339
- content = "";
340
- }
341
-
342
- resData.content = content;
343
- resData.status = status || 200;
344
- resData.headers = headers || {};
345
- resData.contentType = contentType || this.res.get("Content-Type");
346
- resData.lien = this;
347
-
348
- var trans = this.server.getHooks("after", this.path, this.method);
349
-
350
- if (trans) {
351
- trans.start(resData, function (err, data) {
352
- if (err) {
353
- data.content = err;
354
- }
355
- _this2._sendResponse(data);
356
- });
357
- } else {
358
- this._sendResponse(resData);
359
- }
360
- }
361
-
362
- /*!
363
- * _sendResponse
364
- * Low level function for sending the response.
365
- *
366
- * @name _sendResponse
367
- * @function
368
- * @param {Object} resData An object containing the following fields:
369
- *
370
- * - `content` (Anything): The data to send to client.
371
- * - `status` (Number): The response status.
372
- * - `headers` (Object): The headers object.
373
- * - `contentType` (String): The content type.
374
- *
375
- */
376
-
377
- }, {
378
- key: "_sendResponse",
379
- value: function _sendResponse(resData) {
380
-
381
- if (this.res.headersSent) {
382
- return;
383
- }
384
-
385
- if (resData.content && resData.content.statusCode) {
386
- resData.status = resData.content.statusCode;
387
- }
388
-
389
- var bRes = toBuffer(resData.content);
390
-
391
- this.res.status(resData.status);
392
- this.header(resData.headers);
393
-
394
- this.res.type(resData.contentType || bRes.contentType);
395
- this.res.end(bRes.buffer);
396
- }
397
-
398
- /**
399
- * cookie
400
- * Sets, gets or deletes the cookie.
401
- *
402
- * @name cookie
403
- * @function
404
- * @param {String} cookie The searched cookie.
405
- * @param {String} value If provided and it not `null`, the cookie will be set. If it's null, the cookie will be deleted. If `value` is not provided, the cookie value will be returned.
406
- * @return {String|null|undefined} `null`, if the cookie was deleted. `undefined` if the cookie doesn't exist. The cookie value if this exists.
407
- */
408
-
409
- }, {
410
- key: "cookie",
411
- value: function cookie(name, value, options) {
412
- if (value === undefined) {
413
- return this.cookies[name];
414
- }
415
-
416
- if (value === null) {
417
- this.res.clearCookie(name);
418
- } else {
419
- this.res.cookie(name, value, options);
420
- }
421
-
422
- return this;
423
- }
424
-
425
- /**
426
- * file
427
- * Serves a file to the response.
428
- *
429
- * @name file
430
- * @function
431
- * @param {String} path Relative path to the file.
432
- * @param {String} customRoot Absolute path to the root directory (optional).
433
- */
434
-
435
- }, {
436
- key: "file",
437
- value: function file(filePath, customRoot) {
438
- if (!customRoot) {
439
- customRoot = this.server.options.public[0][1];
440
- }
441
- filePath = path.resolve(customRoot, filePath);
442
- this.res.sendFile(filePath);
443
- }
444
- }]);
445
-
446
- return LienObj;
447
- }();
448
-
449
- var RESPONSE_METHODS = ["append", "attachment", "download", "json", "jsonp", "links", "vary", "status"];
450
- RESPONSE_METHODS.forEach(function (method) {
451
- LienObj.prototype[method] = function () {
452
- this.res[method].apply(this.res, arguments);
453
- return this;
454
- };
455
- });
1
+ import Lien from "./server.js";
2
+ import Hooks from "./hooks.js";
3
+ import LienObj from "./lien.js";
456
4
 
457
5
  /**
458
- * Lien
459
- * Creates a new Lien instance.
460
- *
461
- * It extends the `EventEmitter` class.
462
- *
463
- * It emits the following events:
464
- *
465
- * - `load` (err): After the server is started. If there are no errors, the `err` will be null.
466
- * - `serverError` (err, req, res): This is emitted when something goes wrong after the server is started.
467
- * - `error` (err): Errors which may appear during the server initialization.
468
- *
469
- * @name Lien
470
- * @function
471
- * @param {Object} opt_options An object containing the following properties:
472
- *
473
- * - `host` (String): The server host.
474
- * - `port` (Integer): The server port. `process.env.PORT` is used, default is `3000`.
475
- * - `session` (Boolean|Object): Enable the session support. If it's an object, it will be merged with the following defaults and passed to [`express-session`](https://github.com/expressjs/session):
476
- * - `secret` (String): This is the secret used to sign the session ID cookie (default: "lien server").
477
- * - `resave` (Boolean): Forces the session to be saved back to the session store, even if the session was never modified during the request (default: false).
478
- * - `saveUninitialized` (Boolean): Forces a session that is "uninitialized" to be saved to the store (default: `true`).
479
- * - `cookie` (Object): The cookie [options](https://github.com/expressjs/cookie-parser).
480
- * - `storeOptions` (Object): The session store options. These options are passed to the session store you choose.
481
- * - `store`: (String|Function): The session store name or function. By default it's using a memory store if the session is enabled.
482
- * - `public` (String|Array): The path to the public directory or an array of arrays in this format: `["/url/of/static/dir", "path/to/static/dir"]`.
483
- *
484
- * Example:
485
- *
486
- * ```js
487
- * [
488
- * ["/images", "path/to/images"]
489
- * , ["/", "path/to/public"]
490
- * ]
491
- * ```
492
- *
493
- * - `ssl` (Object): An object containing the following fields:
494
- * - `key` (String): The path to the key file.
495
- * - `cert` (String): The path to the cert file.
496
- * - `_key` (String|Buffer): The key file content (defaults to the key file content).
497
- * - `_cert` (String|Buffer): The cert file content (defaults to the cert file content).
498
- *
499
- * - `views`
500
- * - `path` (String): The path to the views directory.
501
- * - `name` (String): The view engine name.
502
- *
503
- * - `errorPages` (Object):
504
- * - `notFound` (String|Function): The path to a custom 404 page or a function receiving the lien object as parameter. This can be used to serve custom 404 pages.
505
- * - `serverError` (String|Function): The path to a custom 500 page or a function receiving the lien object as parameter. This can be used to serve custom 500 pages.
506
- * - `badCsrf` (String|Function): The path to a custom bad CSRF page or a function receiving the lien object as parameter. This can be used to serve custom bad CSRF errors.
507
- *
508
- * - `logErrors` (Boolean): Log the server errors (default: `true`).
509
- * - `csrf` (Object): The CSRF options. These are passed to [`csurf`](https://github.com/expressjs/csurf)
510
- * - `bodyParserJson` (Boolean): Whether to enable the JSON body parser (default: `true`)
511
- * - `bodyParserUrlEncoded` (Boolean): Whether to enable the URL encoded body parser (default: `true`)
512
- * - `cookieParser` (Boolean): Whether to enable the cookie parser (default: `true`)
513
- * - `transformers` (Boolean): Whether to enable the transformers (default: `true`)
514
- *
515
- * @return {Object} The Lien instance.
6
+ * The constructor for reusable hook pipelines.
7
+ * @type {typeof Hooks}
516
8
  */
9
+ Lien.Hooks = Hooks;
10
+ /**
11
+ * The request object constructor, also available as a named export.
12
+ * @type {typeof LienObj}
13
+ */
14
+ Lien.LienObj = LienObj;
517
15
 
518
- var Lien = function (_EventEmitter) {
519
- _inherits(Lien, _EventEmitter);
520
-
521
- function Lien(options) {
522
- var _this3$server;
523
-
524
- _classCallCheck(this, Lien);
525
-
526
- var _this3 = _possibleConstructorReturn(this, (Lien.__proto__ || Object.getPrototypeOf(Lien)).call(this));
527
-
528
- options = ul.merge(options, {
529
- public: [],
530
- session: false,
531
- errorPages: {},
532
- logErrors: true,
533
- csrf: null,
534
- port: process.env.PORT || 3000,
535
- cookieSecret: "lien",
536
- cookieOptions: {},
537
- bodyParserJson: true,
538
- bodyParserUrlEncoded: true,
539
- cookieParser: true,
540
- transformers: true
541
- });
542
-
543
- if (options.csrf === true) {
544
- options.csrf = {
545
- cookie: true
546
- };
547
- }
548
-
549
- _this3.csrf = options.csrf ? csrf(options.csrf) : null;
550
- _this3.express = express;
551
- _this3.router = express.Router();
552
- _this3.beforeRequest = express.Router();
553
- _this3.staticRouter = express.Router();
554
-
555
- _this3.transformers = {
556
- before: {},
557
- after: {}
558
- };
559
-
560
- var app = _this3.app = express();
561
-
562
- if (options.views) {
563
- app.set("views", options.views.path);
564
- app.set("view engine", options.views.name);
565
- }
566
-
567
- options.bodyParserJson && app.use(bodyParser.json());
568
- options.bodyParserUrlEncoded && app.use(bodyParser.urlencoded({ extended: true }));
569
-
570
- app.disable("x-powered-by");
571
-
572
- _this3.SessionStore = null;
573
- _this3.SessionStoreModule = null;
574
-
575
- options.cookieParser && app.use(cookieParser(options.cookieSecret, options.cookieOptions));
576
-
577
- if (options.session) {
578
- options.session = ul.merge(options.session, {
579
- resave: false,
580
- saveUninitialized: true,
581
- store: null,
582
- storeOptions: {}
583
- });
584
- options.session.secret = options.cookieSecret;
585
-
586
- // Store name provided
587
- if (typeof options.session.store === "string") {
588
- try {
589
- _this3.SessionStoreModule = require(options.session.store);
590
- } catch (e) {
591
- if (e.code === "MODULE_NOT_FOUND") {
592
- _this3.emit("error", new Error("The " + options.session.store + " should be installed in your app to use it as session store."));
593
- } else {
594
- _this3.emit("error", e);
595
- }
596
- }
597
- } else if (typeof options.session.store === "function") {
598
- _this3.SessionStoreModule = options.session.store;
599
- }
600
-
601
- if (!_this3.SessionStoreModule && options.session.storeOptions) {
602
- console.warn("Received store options, but no store was specified.");
603
- }
604
-
605
- if (_this3.SessionStoreModule && options.session.storeOptions) {
606
- _this3.SessionStore = _this3.SessionStoreModule(session);
607
- options.session.store = new _this3.SessionStore(options.session.storeOptions);
608
- } else if (!_this3.SessionStoreModule && _this3.app.get("env") === "production") {
609
- console.warn("You are using a memory session store in production. This may cause memory leaks. Please consider using a database store.");
610
- }
611
-
612
- _this3.session = session(options.session);
613
- _this3.app.use(_this3.session);
614
- }
615
-
616
- // Handle ssl
617
- if (options.ssl) {
618
- options.ssl._key = options.ssl._key || fs.readFileSync(options.ssl.key);
619
- options.ssl._cert = options.ssl._cert || fs.readFileSync(options.ssl.cert);
620
- _this3.server = https.createServer({
621
- key: options.ssl._key,
622
- cert: options.ssl._cert
623
- }, _this3.app);
624
- } else {
625
- _this3.server = http.createServer(_this3.app);
626
- }
627
-
628
- if (!Array.isArray(options.public)) {
629
- options.public = [["/", options.public]];
630
- }
631
-
632
- _this3.options = options;
633
-
634
- app.use(_this3.beforeRequest);
635
- app.use(_this3.staticRouter);
636
- app.use(_this3.router);
637
-
638
- // Public directorie
639
- options.public.forEach(function (c) {
640
- _this3.addStaticPath(c[0], c[1]);
641
- });
642
-
643
- var listenArgs = [options.port];
644
-
645
- if (options.host) {
646
- listenArgs.push(options.host);
647
- }
648
-
649
- listenArgs.push(function (err) {
650
- _this3.emit("load", err);
651
- });
652
-
653
- ["all"].concat(httpMethods).forEach(function (method) {
654
- if (_this3[method]) {
655
- return;
656
- }
657
- _this3[method] = function (url, output) {
658
- _this3.addPage(url, method, output);
659
- };
660
- });
661
-
662
- // Start listening on host:port
663
- (_this3$server = _this3.server).listen.apply(_this3$server, listenArgs);
664
-
665
- if (options.errorPages) {
666
- process.nextTick(function () {
667
- _this3.errorPages(options.errorPages);
668
- });
669
- }
670
- return _this3;
671
- }
672
-
673
- /**
674
- * addStaticPath
675
- * Adds a new static path to the server.
676
- *
677
- * @name addStaticPath
678
- * @function
679
- * @static
680
- * @param {String} url The static path url endpoint.
681
- * @param {String} localPath The local path to the directory.
682
- */
683
-
684
-
685
- _createClass(Lien, [{
686
- key: "addStaticPath",
687
- value: function addStaticPath(url, localPath) {
688
- this.staticRouter.use(url, express.static(localPath));
689
- }
690
-
691
- /*!
692
- * _handleRoute
693
- * Calls a function or serves a static file.
694
- *
695
- * @name _handleRoute
696
- * @function
697
- * @param {Request} req The request object.
698
- * @param {Response} res The response object.
699
- * @param {String|Function} output The path to a public file or a function.
700
- * @param {Array} args An array of custom arguments to be used in the function call.
701
- */
702
-
703
- }, {
704
- key: "_handleRoute",
705
- value: function _handleRoute(req, res, output, args, next) {
706
- var lien = new LienObj(req, res, next || noop, this);
707
-
708
- if (typeof output === "string") {
709
- return lien.file(output);
710
- }
711
-
712
- if (Array.isArray(args)) {
713
- args.unshift(lien);
714
- } else {
715
- args = [lien];
716
- }
717
-
718
- output.apply(this, args);
719
- }
720
-
721
- /*!
722
- * _handleLienRoute
723
- *
724
- * @name _handleLienRoute
725
- * @function
726
- * @param {Lien} lien The Lien instance.
727
- * @param {Function} output The route handler.
728
- */
729
-
730
- }, {
731
- key: "_handleLienRoute",
732
- value: function _handleLienRoute(lien, output) {
733
- if (typeof output === "string") {
734
- return lien.file(output);
735
- }
736
- output.apply(this, [lien]);
737
- }
738
-
739
- /**
740
- * addPage
741
- * Adds a new page to be handled.
742
- *
743
- * @name addPage
744
- * @function
745
- * @param {String} url The page url.
746
- * @param {String|Object} method The request methods to be handled (default: `"all"`) or an object:
747
- *
748
- * - `method` (String): The HTTP method.
749
- * - `before` (Array|Function): A function or an array of middleware functions to be executed *before* the main function.
750
- * - `after` (Array|Function): A function or an array of middleware functions to be executed *after* the main function.
751
- *
752
- * @param {Function} output A function receiving the `lien` object as parameter. If can be a path serving a public file.
753
- */
754
-
755
- }, {
756
- key: "addPage",
757
- value: function addPage(url, method, output) {
758
- var _this4 = this;
759
-
760
- if (output === undefined) {
761
- output = method;
762
- method = "all";
763
- }
764
-
765
- var router = typeof url === "string" && ~url.indexOf(":") ? this.router : this.beforeRequest;
766
- var before = [this.csrf];
767
- var after = [];
768
- if (method && method.method) {
769
- before = method.before || [];
770
- if (!Array.isArray(before)) {
771
- before = [before];
772
- }
773
- after = method.after || [];
774
- if (!Array.isArray(after)) {
775
- after = [after];
776
- }
777
- method = method.method;
778
- }
779
- var funcs = [].concat(before);
780
- if (this.options.transformers) {
781
- funcs.push(function (req, res, next) {
782
- var trans = _this4.getHooks("before", req.path, req.method.toLowerCase());
783
- if (trans) {
784
- var lien = new LienObj(req, res, next, _this4);
785
- trans.start(lien, function (err, data) {
786
- if (err) {
787
- return lien.end(err);
788
- }
789
- _this4._handleLienRoute(lien, output);
790
- });
791
- } else {
792
- _this4._handleRoute(req, res, output, [], next);
793
- }
794
- });
795
- } else {
796
- funcs.push(function (req, res, next) {
797
- _this4._handleRoute(req, res, output, [], next);
798
- });
799
- }
800
- funcs = funcs.concat(after);
801
-
802
- router[method].apply(router, [url].concat(funcs.filter(Boolean)));
803
- }
804
-
805
- /**
806
- * errorPages
807
- * Handle the error pages.
808
- *
809
- * @name errorPages
810
- * @function
811
- * @param {Object} options An object containing the following fields:
812
- *
813
- * - `notFound` (String|Function): The path to a custom 404 page or a function receiving the lien object as parameter. This can be used to serve custom 404 pages.
814
- * - `serverError` (String|Function): The path to a custom 500 page or a function receiving the lien object as parameter. This can be used to serve custom 500 pages.
815
- */
816
-
817
- }, {
818
- key: "errorPages",
819
- value: function errorPages(options) {
820
- var _this5 = this;
821
-
822
- var sendResp = function sendResp(lien, msg, status) {
823
- if (lien.accepts("html")) {
824
- return lien.end(msg, status);
825
- } else if (lien.accepts("json")) {
826
- return lien.apiError(msg, status);
827
- }
828
- lien.end(msg, status, "txt");
829
- };
830
- options = ul.merge(options, {
831
- notFound: function notFound(lien) {
832
- return sendResp(lien, "404 — Not found.", 404);
833
- },
834
- serverError: function serverError(lien) {
835
- return sendResp(lien, "500 — Internal Server Error", 500);
836
- },
837
- badCsrf: function badCsrf(lien) {
838
- return sendResp(lien, "What‽ Your browser did something unexpected.", 422);
839
- }
840
- });
841
- this.app.use(function (req, res, next) {
842
- _this5._handleRoute(req, res, options.notFound, [], next);
843
- });
844
- this.app.use(function (err, req, res, next) {
845
- if (err.code === "ENOENT" || err.statusCode === 404) {
846
- return _this5._handleRoute(req, res, options.notFound, [err], next);
847
- }
848
- if (err.code === "EBADCSRFTOKEN") {
849
- return _this5._handleRoute(req, res, options.badCsrf, [err], next);
850
- }
851
-
852
- _this5.emit("serverError", err, req, res);
853
- if (_this5.options.logErrors) {
854
- console.error(err.stack);
855
- }
856
- _this5._handleRoute(req, res, options.serverError, [err], next);
857
- });
858
- }
859
-
860
- /**
861
- * getHooks
862
- * Gets the transformer for a url.
863
- *
864
- * @name getHooks
865
- * @function
866
- * @param {String} type The hook type (`before` or `after`).
867
- * @param {String} url The url.
868
- * @param {String} method The method.
869
- * @returns {Transformer|null} The transformer (if it exists) or `null`.
870
- */
871
-
872
- }, {
873
- key: "getHooks",
874
- value: function getHooks(type, url, method) {
875
- var typ = this.transformers[type] = this.transformers[type] || {},
876
- all = setOrGet(typ, method, []),
877
- hooks = [];
878
-
879
- for (var i = 0, c; i < all.length; ++i) {
880
- c = all[i];
881
- if (c.re.test(url)) {
882
- hooks.push(c.trans);
883
- }
884
- }
885
-
886
- if (hooks.length) {
887
- if (hooks.length === 1) {
888
- return hooks[0];
889
- }
890
- return new Transformer({}, { autostart: false }).add(hooks, Transformer.PARALLEL);
891
- }
892
-
893
- return null;
894
- }
895
-
896
- /**
897
- * getHooksStrict
898
- * Similar to `getHooks`, but doesn't concat hooks based on the regex
899
- * matching but only if they are the same regex.
900
- *
901
- * @name getHooksStrict
902
- * @function
903
- * @param {String} type The hook type (`before` or `after`).
904
- * @param {String} url The url.
905
- * @param {String} method The method.
906
- * @returns {Transformer|null} The transformer (if it exists) or `null`.
907
- */
908
-
909
- }, {
910
- key: "getHooksStrict",
911
- value: function getHooksStrict(type, url, method) {
912
- if (url === "*") {
913
- url = "(.*)";
914
- }
915
- var reUrl = pathToRegexp(url),
916
- typ = this.transformers[type] = this.transformers[type] || {},
917
- all = setOrGet(typ, method, []),
918
- hooks = [];
919
-
920
- for (var i = 0, c; i < all.length; ++i) {
921
- c = all[i];
922
- if (c.re.toString() === reUrl.toString()) {
923
- hooks.push(c.trans);
924
- }
925
- }
926
-
927
- if (hooks.length) {
928
- if (hooks.length === 1) {
929
- return hooks[0];
930
- }
931
- return new Transformer({}, { autostart: false }).add(hooks, Transformer.PARALLEL);
932
- }
933
-
934
- return null;
935
- }
936
-
937
- /**
938
- * insertHook
939
- * Inserts a new hook.
940
- *
941
- * @name insertHook
942
- * @function
943
- * @param {String} type The hook type (`before`, `after`, `custom:name`).
944
- * @param {String} url The url.
945
- * @param {String} method The method.
946
- * @param {Transformer} trans The transformer to insert.
947
- * @returns {Transformer} The inserted transformer.
948
- */
949
-
950
- }, {
951
- key: "insertHook",
952
- value: function insertHook(type, url, method, trans) {
953
-
954
- if (url === "*") {
955
- url = "(.*)";
956
- }
957
-
958
- var all = setOrGet(this.transformers[type], method, []);
959
-
960
- all.push({
961
- re: pathToRegexp(url),
962
- trans: trans
963
- });
964
-
965
- return trans;
966
- }
967
-
968
- /**
969
- * hook
970
- * Adds a new hook.
971
- *
972
- * @name hook
973
- * @function
974
- * @param {String} where The hook type (`before` or `after`).
975
- * @param {String} url The route url.
976
- * @param {String} method The HTTP method.
977
- * @param {Function} cb The callback function.
978
- * @param {Number} transType The transformer type.
979
- */
980
-
981
- }, {
982
- key: "hook",
983
- value: function hook(where, url, method, cb, transType) {
984
- var _this6 = this;
985
-
986
- if (!this.options.transformers) {
987
- console.warn("Transformers are disabled.");
988
- }
989
-
990
- if (typeof url === "string" && url.charAt(0) === ":") {
991
- url = "/" + url;
992
- }
993
- if (typeof method === "function") {
994
- cb = method;
995
- method = "all";
996
- }
997
-
998
- if (method === "all") {
999
- httpMethods.forEach(function (c) {
1000
- return _this6.hook(where, url, c, cb, transType);
1001
- });
1002
- return this;
1003
- }
1004
-
1005
- if (Array.isArray(url)) {
1006
- url.forEach(function (u) {
1007
- return _this6.hook(where, u, method, cb, transType);
1008
- });
1009
- return this;
1010
- }
1011
-
1012
- var customName = where.split(":");
1013
-
1014
- var trans = {};
1015
- setOrGet(this.transformers, where, {});
1016
- switch (customName[0]) {
1017
- case "before":
1018
- case "after":
1019
- case "custom":
1020
- trans = this.getHooksStrict(where, url, method) || this.insertHook(where, url, method, new Transformer({}, { autostart: false }));
1021
- break;
1022
- default:
1023
- throw new Error("The hook type should be 'before', 'after' or 'custom'.");
1024
- break;
1025
- }
1026
-
1027
- trans.add(cb, transType);
1028
- return this;
1029
- }
1030
-
1031
- /**
1032
- * before
1033
- * Adds a before hook. It will handle all the subroutes of the `url`.
1034
- *
1035
- * @name before
1036
- * @function
1037
- * @param {String} url The route url.
1038
- * @param {String} method The HTTP method.
1039
- * @param {Function} cb The callback function.
1040
- * @param {Number} transType The transformer type.
1041
- */
1042
-
1043
- }, {
1044
- key: "before",
1045
- value: function before(url, method, cb, transType) {
1046
- this.hook("before", url, method, cb, transType);
1047
- }
1048
-
1049
- /**
1050
- * after
1051
- * Adds a before hook. It will handle all the subroutes of the `url`.
1052
- *
1053
- * @name after
1054
- * @function
1055
- * @param {String} url The route url.
1056
- * @param {String} method The HTTP method.
1057
- * @param {Function} cb The callback function.
1058
- * @param {Number} transType The transformer type.
1059
- */
1060
-
1061
- }, {
1062
- key: "after",
1063
- value: function after(url, method, cb, transType) {
1064
- this.hook("after", url, method, cb, transType);
1065
- }
1066
-
1067
- /**
1068
- * use
1069
- * Use this function to add middleware handlers.
1070
- *
1071
- * @name use
1072
- * @function
1073
- * @param {String} url The route url.
1074
- * @param {String} method The HTTP method.
1075
- * @param {Function} cb The callback function.
1076
- * @param {Number} transType The transformer type.
1077
- */
1078
-
1079
- }, {
1080
- key: "use",
1081
- value: function use(url, method, cb, transType) {
1082
- if (url.charAt(url.length - 1) === "/") {
1083
- url = url.slice(0, -1);
1084
- }
1085
- this.before([url, url + "/(.*)"], method, cb, transType);
1086
- }
1087
-
1088
- /**
1089
- * add
1090
- * Adds a new middleware. **Note**: This will *not* trigger the hooks.
1091
- *
1092
- * @name add
1093
- * @function
1094
- * @param {String} url The endpoint url.
1095
- * @param {String} method The HTTP method (default: `all`).
1096
- * @param {Function} cb The callback function.
1097
- */
1098
-
1099
- }, {
1100
- key: "add",
1101
- value: function add(url, method, cb) {
1102
- var _this7 = this;
1103
-
1104
- if (typeof method === "function") {
1105
- cb = method;
1106
- method = "all";
1107
- }
1108
- this.router[method].call(this.router, url, function (req, res, next) {
1109
- var lien = new LienObj(req, res, next, _this7);
1110
- cb(lien);
1111
- });
1112
- }
1113
- }]);
1114
-
1115
- return Lien;
1116
- }(EventEmitter);
16
+ export { Lien, Hooks, LienObj };
17
+ export default Lien;
1117
18
 
1118
- Lien.LienObj = LienObj;
1119
- module.exports = Lien;
19
+ // Keep require("lien") returning the constructor.
20
+ export { Lien as "module.exports" };