@kaito-http/core 2.2.6 → 2.3.1

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.
@@ -1,42 +1,21 @@
1
- import http from 'http';
1
+ import * as http from 'http';
2
+ import fmw from 'find-my-way';
2
3
  import { TLSSocket } from 'tls';
3
4
  import getRawBody from 'raw-body';
4
5
 
5
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
6
- try {
7
- var info = gen[key](arg);
8
- var value = info.value;
9
- } catch (error) {
10
- reject(error);
11
- return;
12
- }
13
-
14
- if (info.done) {
15
- resolve(value);
16
- } else {
17
- Promise.resolve(value).then(_next, _throw);
18
- }
19
- }
20
-
21
- function _asyncToGenerator(fn) {
22
- return function () {
23
- var self = this,
24
- args = arguments;
25
- return new Promise(function (resolve, reject) {
26
- var gen = fn.apply(self, args);
27
-
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
-
32
- function _throw(err) {
33
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
- }
35
-
36
- _next(undefined);
37
- });
6
+ function createFMWServer(config) {
7
+ var fmw = config.router.toFindMyWay(config);
8
+ var server = http.createServer((req, res) => {
9
+ fmw.lookup(req, res);
10
+ });
11
+ return {
12
+ server,
13
+ fmw
38
14
  };
39
15
  }
16
+ function createServer(config) {
17
+ return createFMWServer(config).server;
18
+ }
40
19
 
41
20
  function _defineProperty(obj, key, value) {
42
21
  if (key in obj) {
@@ -91,6 +70,42 @@ function _objectSpread2(target) {
91
70
  return target;
92
71
  }
93
72
 
73
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
74
+ try {
75
+ var info = gen[key](arg);
76
+ var value = info.value;
77
+ } catch (error) {
78
+ reject(error);
79
+ return;
80
+ }
81
+
82
+ if (info.done) {
83
+ resolve(value);
84
+ } else {
85
+ Promise.resolve(value).then(_next, _throw);
86
+ }
87
+ }
88
+
89
+ function _asyncToGenerator(fn) {
90
+ return function () {
91
+ var self = this,
92
+ args = arguments;
93
+ return new Promise(function (resolve, reject) {
94
+ var gen = fn.apply(self, args);
95
+
96
+ function _next(value) {
97
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
98
+ }
99
+
100
+ function _throw(err) {
101
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
102
+ }
103
+
104
+ _next(undefined);
105
+ });
106
+ };
107
+ }
108
+
94
109
  class WrappedError extends Error {
95
110
  static maybe(maybeError) {
96
111
  if (maybeError instanceof Error) {
@@ -110,7 +125,17 @@ class WrappedError extends Error {
110
125
  }
111
126
 
112
127
  }
128
+ class KaitoError extends Error {
129
+ constructor(status, message) {
130
+ super(message);
131
+ this.status = status;
132
+ }
113
133
 
134
+ }
135
+
136
+ function createGetContext(callback) {
137
+ return callback;
138
+ }
114
139
  function getLastEntryInMultiHeaderValue(headerValue) {
115
140
  var normalized = Array.isArray(headerValue) ? headerValue.join(',') : headerValue;
116
141
  var lastIndex = normalized.lastIndexOf(',');
@@ -128,8 +153,7 @@ function normalizePath(path) {
128
153
  }
129
154
 
130
155
  return result;
131
- } // Type for import('http').METHODS
132
-
156
+ }
133
157
  function getInput(_x) {
134
158
  return _getInput.apply(this, arguments);
135
159
  }
@@ -165,6 +189,8 @@ function _getInput() {
165
189
 
166
190
  class KaitoRequest {
167
191
  constructor(raw) {
192
+ _defineProperty(this, "_url", null);
193
+
168
194
  this.raw = raw;
169
195
  }
170
196
 
@@ -175,7 +201,12 @@ class KaitoRequest {
175
201
  }
176
202
 
177
203
  get url() {
178
- return new URL(this.fullURL);
204
+ if (this._url) {
205
+ return this._url;
206
+ }
207
+
208
+ this._url = new URL(this.fullURL);
209
+ return this._url;
179
210
  }
180
211
 
181
212
  get method() {
@@ -231,141 +262,34 @@ class KaitoResponse {
231
262
 
232
263
  }
233
264
 
234
- function createGetContext(getContext) {
235
- return getContext;
236
- }
237
265
  class Router {
238
- static patternize(path) {
239
- var normalized = normalizePath(path);
240
- return new RegExp("^".concat(normalized, "/?$"), 'i');
241
- }
242
-
243
- constructor(procs) {
244
- _defineProperty(this, "create", method => (path, proc) => {
245
- var pattern = Router.patternize(path);
246
-
247
- var merged = _objectSpread2(_objectSpread2({}, this.procs), {}, {
248
- [path]: _objectSpread2(_objectSpread2({}, proc), {}, {
249
- method,
250
- path,
251
- pattern
252
- })
253
- });
254
-
255
- return new Router(merged);
256
- });
257
-
258
- _defineProperty(this, "merge", (prefix, router) => {
259
- var newProcs = Object.entries(router.getProcs()).reduce((all, entry) => {
260
- var [path, proc] = entry;
261
- var newPath = "".concat(prefix).concat(path);
262
- return _objectSpread2(_objectSpread2({}, all), {}, {
263
- ["".concat(prefix).concat(path)]: _objectSpread2(_objectSpread2({}, proc), {}, {
264
- path: newPath,
265
- pattern: Router.patternize(newPath)
266
- })
267
- });
268
- }, {});
269
-
270
- var mergedProcs = _objectSpread2(_objectSpread2({}, this.procs), newProcs);
271
-
272
- return new Router(mergedProcs);
273
- });
274
-
275
- _defineProperty(this, "get", this.create('GET'));
276
-
277
- _defineProperty(this, "post", this.create('POST'));
278
-
279
- _defineProperty(this, "put", this.create('PUT'));
280
-
281
- _defineProperty(this, "patch", this.create('PATCH'));
282
-
283
- _defineProperty(this, "delete", this.create('DELETE'));
284
-
285
- _defineProperty(this, "head", this.create('HEAD'));
286
-
287
- _defineProperty(this, "options", this.create('OPTIONS'));
288
-
289
- _defineProperty(this, "connect", this.create('CONNECT'));
290
-
291
- _defineProperty(this, "trace", this.create('TRACE'));
292
-
293
- _defineProperty(this, "acl", this.create('ACL'));
294
-
295
- _defineProperty(this, "bind", this.create('BIND'));
296
-
297
- this.procs = procs;
298
- this._procsArray = Object.values(procs);
266
+ static create() {
267
+ return new Router({});
299
268
  }
300
269
 
301
- getProcs() {
302
- return this.procs;
303
- }
304
-
305
- find(method, url) {
306
- for (var proc of this._procsArray) {
307
- if (proc.method !== method) {
308
- continue;
309
- }
310
-
311
- if (proc.pattern.test(url)) {
312
- return proc;
313
- }
314
- }
315
-
316
- return null;
317
- }
318
-
319
- }
320
- class KaitoError extends Error {
321
- constructor(status, message, cause) {
322
- super(message);
323
- this.status = status;
324
- this.cause = cause;
325
- }
326
-
327
- }
328
- function createRouter() {
329
- return new Router({});
330
- }
331
- function createServer(config) {
332
- var log = message => {
333
- if (config.log === undefined) {
334
- console.log(message);
335
- } else if (config.log) {
336
- config.log(message);
337
- }
338
- };
339
-
340
- return http.createServer( /*#__PURE__*/function () {
341
- var _ref = _asyncToGenerator(function* (incomingMessage, serverResponse) {
342
- var start = Date.now();
343
- var req = new KaitoRequest(incomingMessage);
344
- var res = new KaitoResponse(serverResponse);
345
-
270
+ static handle(server, options) {
271
+ return _asyncToGenerator(function* () {
346
272
  try {
347
- var _handler$input, _yield$getInput;
348
-
349
- var handler = config.router.find(req.method, req.url.pathname);
273
+ var _options$route$input$, _options$route$input;
350
274
 
351
- if (!handler) {
352
- throw new KaitoError(404, "Cannot ".concat(req.method, " this route."));
353
- }
354
-
355
- var input = (_handler$input = handler.input) === null || _handler$input === void 0 ? void 0 : _handler$input.parse((_yield$getInput = yield getInput(req)) !== null && _yield$getInput !== void 0 ? _yield$getInput : undefined);
356
- var context = yield config.getContext(req, res);
357
- var data = yield handler.run({
275
+ var context = yield server.getContext(options.req, options.res);
276
+ var body = yield getInput(options.req);
277
+ var input = (_options$route$input$ = (_options$route$input = options.route.input) === null || _options$route$input === void 0 ? void 0 : _options$route$input.parse(body)) !== null && _options$route$input$ !== void 0 ? _options$route$input$ : undefined;
278
+ var result = yield options.route.run({
358
279
  ctx: context,
359
- input
280
+ input,
281
+ params: options.params
360
282
  });
361
- res.json({
283
+ options.res.status(200).json({
362
284
  success: true,
363
- data,
285
+ data: result,
364
286
  message: 'OK'
365
287
  });
366
- } catch (error) {
288
+ } catch (e) {
289
+ var error = WrappedError.maybe(e);
290
+
367
291
  if (error instanceof KaitoError) {
368
- res.status(error.status).json({
292
+ options.res.status(error.status).json({
369
293
  success: false,
370
294
  data: null,
371
295
  message: error.message
@@ -374,31 +298,110 @@ function createServer(config) {
374
298
  }
375
299
 
376
300
  var {
377
- status: _status,
378
- message: _message
379
- } = yield config.onError({
380
- error: WrappedError.maybe(error),
381
- req,
382
- res
301
+ status,
302
+ message
303
+ } = yield server.onError({
304
+ error,
305
+ req: options.req,
306
+ res: options.res
383
307
  }).catch(() => ({
384
308
  status: 500,
385
- message: 'Something went wrong'
309
+ message: 'Internal Server Error'
386
310
  }));
387
- res.status(_status).json({
311
+ options.res.status(status).json({
388
312
  success: false,
389
313
  data: null,
390
- message: _message
314
+ message
391
315
  });
392
- } finally {
393
- var finish = Date.now();
394
- log("".concat(req.method, " ").concat(req.fullURL, " ").concat(res.raw.statusCode, " ").concat(finish - start, "ms"));
395
316
  }
396
- });
317
+ })();
318
+ }
319
+
320
+ constructor(routes) {
321
+ _defineProperty(this, "get", this.make('GET'));
322
+
323
+ _defineProperty(this, "post", this.make('POST'));
324
+
325
+ _defineProperty(this, "head", this.make('HEAD'));
326
+
327
+ _defineProperty(this, "put", this.make('PUT'));
328
+
329
+ _defineProperty(this, "patch", this.make('PATCH'));
330
+
331
+ this.routes = routes;
332
+ }
333
+
334
+ merge(prefix, router) {
335
+ var newRoutes = Object.fromEntries(Object.entries(router.routes).map(_ref => {
336
+ var [k, v] = _ref;
337
+ return ["".concat(prefix).concat(k), v];
338
+ }));
339
+ return new Router(_objectSpread2(_objectSpread2({}, this.routes), newRoutes));
340
+ }
341
+
342
+ toFindMyWay(server) {
343
+ var _this = this;
344
+
345
+ var instance = fmw({
346
+ ignoreTrailingSlash: true,
397
347
 
398
- return function (_x, _x2) {
399
- return _ref.apply(this, arguments);
348
+ defaultRoute(req, serverResponse) {
349
+ var _req$url;
350
+
351
+ var res = new KaitoResponse(serverResponse);
352
+ res.status(404).json({
353
+ success: false,
354
+ data: null,
355
+ message: "Cannot ".concat(req.method, " ").concat((_req$url = req.url) !== null && _req$url !== void 0 ? _req$url : '/')
356
+ });
357
+ }
358
+
359
+ }); // eslint-disable-next-line guard-for-in
360
+
361
+ var _loop = function _loop(path) {
362
+ var route = _this.routes[path];
363
+ instance.on(route.method, path, /*#__PURE__*/function () {
364
+ var _ref2 = _asyncToGenerator(function* (incomingMessage, serverResponse, params) {
365
+ var req = new KaitoRequest(incomingMessage);
366
+ var res = new KaitoResponse(serverResponse);
367
+ yield Router.handle(server, {
368
+ route,
369
+ params,
370
+ req,
371
+ res
372
+ });
373
+ });
374
+
375
+ return function (_x, _x2, _x3) {
376
+ return _ref2.apply(this, arguments);
377
+ };
378
+ }());
379
+ };
380
+
381
+ for (var path in this.routes) {
382
+ _loop(path);
383
+ }
384
+
385
+ return instance;
386
+ }
387
+
388
+ make(method) {
389
+ return (path, route) => {
390
+ var mergedRoute = _objectSpread2(_objectSpread2({}, route), {}, {
391
+ method
392
+ });
393
+
394
+ return new Router(_objectSpread2(_objectSpread2({}, this.routes), {}, {
395
+ [path]: mergedRoute
396
+ }));
400
397
  };
401
- }());
398
+ }
399
+
402
400
  }
401
+ /**
402
+ * @deprecated Please use Router#create instead
403
+ */
404
+
405
+ var createRouter = Router.create;
403
406
 
404
- export { KaitoError, Router, createGetContext, createRouter, createServer };
407
+ export { KaitoError, KaitoRequest, KaitoResponse, Router, WrappedError, createFMWServer, createGetContext, createRouter, createServer, getInput, getLastEntryInMultiHeaderValue, normalizePath };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaito-http/core",
3
- "version": "2.2.6",
3
+ "version": "2.3.1",
4
4
  "description": "Functional HTTP Framework for TypeScript",
5
5
  "repository": "https://github.com/kaito-http/kaito",
6
6
  "author": "Alistair Smith <hi@alistair.sh>",
@@ -32,6 +32,7 @@
32
32
  "framework"
33
33
  ],
34
34
  "dependencies": {
35
+ "find-my-way": "^5.5.0",
35
36
  "raw-body": "^2.5.1"
36
37
  }
37
38
  }