@wooksjs/event-http 0.2.18 → 0.2.20

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/README.md CHANGED
@@ -10,10 +10,11 @@
10
10
  </p>
11
11
 
12
12
  As a part of `wooks` event processing framework, `@wooksjs/event-http` implements http events and provides composables that let you:
13
- - parse urls search params
14
- - parse cookies
15
- - parse request body (json, url-encoded, form, ...)
16
- - serve files
13
+
14
+ - parse urls search params
15
+ - parse cookies
16
+ - parse request body (json, url-encoded, form, ...)
17
+ - serve files
17
18
 
18
19
  ### The main ideas behind composable functions are:
19
20
 
@@ -24,9 +25,9 @@ As a part of `wooks` event processing framework, `@wooksjs/event-http` implement
24
25
 
25
26
  ### Official Wooks HTTP composables:
26
27
 
27
- - [@wooksjs/http-body](https://github.com/wooksjs/wooksjs/tree/main/packages/http-body) - to parse body
28
- - [@wooksjs/http-static](https://github.com/wooksjs/wooksjs/tree/main/packages/http-static) - to serve static files
29
- - [@wooksjs/http-proxy](https://github.com/wooksjs/wooksjs/tree/main/packages/http-proxy) - to proxy requests
28
+ - [@wooksjs/http-body](https://github.com/wooksjs/wooksjs/tree/main/packages/http-body) - to parse body
29
+ - [@wooksjs/http-static](https://github.com/wooksjs/wooksjs/tree/main/packages/http-static) - to serve static files
30
+ - [@wooksjs/http-proxy](https://github.com/wooksjs/wooksjs/tree/main/packages/http-proxy) - to proxy requests
30
31
 
31
32
  ## Install
32
33
 
@@ -40,12 +41,14 @@ import { createHttpApp } from '@wooksjs/event-http'
40
41
 
41
42
  const app = createHttpApp()
42
43
 
43
- app.on('GET', 'hello/:name', () => `Hello ${ useRouteParams().get('name') }!`)
44
+ app.on('GET', 'hello/:name', () => `Hello ${useRouteParams().get('name')}!`)
44
45
 
45
46
  // shortcuts for some methods are supported:
46
47
  // app.get('hello/:name', () => `Hello ${ useRouteParams().get('name') }!`)
47
48
 
48
- app.listen(3000, () => { console.log('Wooks Server is up on port 3000') })
49
+ app.listen(3000, () => {
50
+ console.log('Wooks Server is up on port 3000')
51
+ })
49
52
  ```
50
53
 
51
54
  ## Documentation
package/dist/index.cjs CHANGED
@@ -39,8 +39,11 @@ function useRequest() {
39
39
  const reqId = eventCore.useEventId().getId;
40
40
  const forwardedIp = () => init('forwardedIp', () => {
41
41
  var _a;
42
- if (typeof req.headers[xForwardedFor] === 'string' && req.headers[xForwardedFor]) {
43
- return (_a = req.headers[xForwardedFor].split(',').shift()) === null || _a === void 0 ? void 0 : _a.trim();
42
+ if (typeof req.headers[xForwardedFor] === 'string' &&
43
+ req.headers[xForwardedFor]) {
44
+ return (_a = req.headers[xForwardedFor]
45
+ .split(',')
46
+ .shift()) === null || _a === void 0 ? void 0 : _a.trim();
44
47
  }
45
48
  else {
46
49
  return '';
@@ -58,8 +61,12 @@ function useRequest() {
58
61
  const getIpList = () => init('ipList', () => {
59
62
  var _a, _b;
60
63
  return {
61
- remoteIp: ((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress) || ((_b = req.connection) === null || _b === void 0 ? void 0 : _b.remoteAddress) || '',
62
- forwarded: (req.headers[xForwardedFor] || '').split(',').map(s => s.trim()),
64
+ remoteIp: ((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress) ||
65
+ ((_b = req.connection) === null || _b === void 0 ? void 0 : _b.remoteAddress) ||
66
+ '',
67
+ forwarded: (req.headers[xForwardedFor] || '')
68
+ .split(',')
69
+ .map((s) => s.trim()),
63
70
  };
64
71
  });
65
72
  return {
@@ -168,7 +175,7 @@ function convertTime(time, unit = 'ms') {
168
175
  const rg = /(\d+)(\w+)/g;
169
176
  let t = 0;
170
177
  let r;
171
- while (r = rg.exec(time)) {
178
+ while ((r = rg.exec(time))) {
172
179
  t += Number(r[1]) * (units[r[2]] || 0);
173
180
  }
174
181
  return t / units[unit];
@@ -206,9 +213,9 @@ function renderCacheControl(data) {
206
213
  const cacheControlFunc = {
207
214
  mustRevalidate: (v) => v ? 'must-revalidate' : '',
208
215
  noCache: (v) => v ? (typeof v === 'string' ? `no-cache="${v}"` : 'no-cache') : '',
209
- noStore: (v) => v ? 'no-store' : '',
210
- noTransform: (v) => v ? 'no-transform' : '',
211
- public: (v) => v ? 'public' : '',
216
+ noStore: (v) => (v ? 'no-store' : ''),
217
+ noTransform: (v) => (v ? 'no-transform' : ''),
218
+ public: (v) => (v ? 'public' : ''),
212
219
  private: (v) => v ? (typeof v === 'string' ? `private="${v}"` : 'private') : '',
213
220
  proxyRevalidate: (v) => v ? 'proxy-revalidate' : '',
214
221
  maxAge: (v) => 'max-age=' + convertTime(v, 's').toString(),
@@ -216,8 +223,10 @@ const cacheControlFunc = {
216
223
  };
217
224
 
218
225
  const renderAge = (v) => convertTime(v, 's').toString();
219
- const renderExpires = (v) => (typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString());
220
- const renderPragmaNoCache = (v) => v ? 'no-cache' : '';
226
+ const renderExpires = (v) => typeof v === 'string' || typeof v === 'number'
227
+ ? new Date(v).toUTCString()
228
+ : v.toUTCString();
229
+ const renderPragmaNoCache = (v) => (v ? 'no-cache' : '');
221
230
  // rfc7234#section-5.2.2
222
231
  function useSetCacheControl() {
223
232
  const { setHeader } = useSetHeaders();
@@ -248,7 +257,7 @@ function useResponse() {
248
257
  const responded = store('response').hook('responded');
249
258
  const statusCode = store('status').hook('code');
250
259
  function status(code) {
251
- return statusCode.value = code ? code : statusCode.value;
260
+ return (statusCode.value = code ? code : statusCode.value);
252
261
  }
253
262
  const rawResponse = (options) => {
254
263
  if (!options || !options.passthrough)
@@ -260,7 +269,7 @@ function useResponse() {
260
269
  hasResponded: () => responded.value || !res.writable || res.writableEnded,
261
270
  status: eventCore.attachHook(status, {
262
271
  get: () => statusCode.value,
263
- set: (code) => statusCode.value = code,
272
+ set: (code) => (statusCode.value = code),
264
273
  }),
265
274
  };
266
275
  }
@@ -284,12 +293,15 @@ function renderCookie(key, data) {
284
293
  return `${key}=${encodeURIComponent(data.value)}${attrs}`;
285
294
  }
286
295
  const cookieAttrFunc = {
287
- expires: (v) => 'Expires=' + (typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString()),
296
+ expires: (v) => 'Expires=' +
297
+ (typeof v === 'string' || typeof v === 'number'
298
+ ? new Date(v).toUTCString()
299
+ : v.toUTCString()),
288
300
  maxAge: (v) => 'Max-Age=' + convertTime(v, 's').toString(),
289
301
  domain: (v) => 'Domain=' + v,
290
302
  path: (v) => 'Path=' + v,
291
- secure: (v) => v ? 'Secure' : '',
292
- httpOnly: (v) => v ? 'HttpOnly' : '',
303
+ secure: (v) => (v ? 'Secure' : ''),
304
+ httpOnly: (v) => (v ? 'HttpOnly' : ''),
293
305
  sameSite: (v) => v ? 'SameSite=' + (typeof v === 'string' ? v : 'Strict') : '',
294
306
  };
295
307
 
@@ -317,7 +329,9 @@ function useCookies() {
317
329
  const getCookie = (name) => init(name, () => {
318
330
  if (cookie) {
319
331
  const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, 'i').exec(cookie);
320
- return result && result[1] ? safeDecodeURIComponent(result[1]) : null;
332
+ return result && result[1]
333
+ ? safeDecodeURIComponent(result[1])
334
+ : null;
321
335
  }
322
336
  else {
323
337
  return null;
@@ -338,7 +352,10 @@ function useSetCookies() {
338
352
  });
339
353
  }
340
354
  function cookies() {
341
- return cookiesStore.entries().filter(a => !!a[1]).map(([key, value]) => renderCookie(key, value));
355
+ return cookiesStore
356
+ .entries()
357
+ .filter((a) => !!a[1])
358
+ .map(([key, value]) => renderCookie(key, value));
342
359
  }
343
360
  return {
344
361
  setCookie,
@@ -368,7 +385,7 @@ class WooksURLSearchParams extends url.URLSearchParams {
368
385
  const json = {};
369
386
  for (const [key, value] of this.entries()) {
370
387
  if (isArrayParam(key)) {
371
- const a = json[key] = (json[key] || []);
388
+ const a = (json[key] = (json[key] || []));
372
389
  a.push(value);
373
390
  }
374
391
  else {
@@ -412,6 +429,8 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
412
429
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
413
430
  PERFORMANCE OF THIS SOFTWARE.
414
431
  ***************************************************************************** */
432
+ /* global Reflect, Promise */
433
+
415
434
 
416
435
  function __awaiter(thisArg, _arguments, P, generator) {
417
436
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -445,7 +464,9 @@ function __asyncValues(o) {
445
464
 
446
465
  class BaseHttpResponseRenderer {
447
466
  render(response) {
448
- if (typeof response.body === 'string' || typeof response.body === 'boolean' || typeof response.body === 'number') {
467
+ if (typeof response.body === 'string' ||
468
+ typeof response.body === 'boolean' ||
469
+ typeof response.body === 'number') {
449
470
  if (!response.getContentType())
450
471
  response.setContentType('text/plain');
451
472
  return response.body.toString();
@@ -643,7 +664,7 @@ class BaseHttpResponse {
643
664
  return this;
644
665
  }
645
666
  setCookie(name, value, attrs) {
646
- const cookies = this._headers['set-cookie'] = (this._headers['set-cookie'] || []);
667
+ const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
647
668
  cookies.push(renderCookie(name, { value, attrs: attrs || {} }));
648
669
  return this;
649
670
  }
@@ -651,7 +672,7 @@ class BaseHttpResponse {
651
672
  this.setHeader('cache-control', renderCacheControl(data));
652
673
  }
653
674
  setCookieRaw(rawValue) {
654
- const cookies = this._headers['set-cookie'] = (this._headers['set-cookie'] || []);
675
+ const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
655
676
  cookies.push(rawValue);
656
677
  return this;
657
678
  }
@@ -668,7 +689,7 @@ class BaseHttpResponse {
668
689
  mergeHeaders() {
669
690
  const { headers } = useSetHeaders();
670
691
  const { cookies, removeCookie } = useSetCookies();
671
- const newCookies = (this._headers['set-cookie'] || []);
692
+ const newCookies = this._headers['set-cookie'] || [];
672
693
  for (const cookie of newCookies) {
673
694
  removeCookie(cookie.slice(0, cookie.indexOf('=')));
674
695
  }
@@ -683,7 +704,9 @@ class BaseHttpResponse {
683
704
  this.status = this.status || useResponse().status();
684
705
  if (!this.status) {
685
706
  const { method } = useRequest();
686
- this.status = renderedBody ? defaultStatus[method] || exports.EHttpStatusCode.OK : exports.EHttpStatusCode.NoContent;
707
+ this.status = renderedBody
708
+ ? defaultStatus[method] || exports.EHttpStatusCode.OK
709
+ : exports.EHttpStatusCode.NoContent;
687
710
  }
688
711
  return this;
689
712
  }
@@ -732,7 +755,8 @@ class BaseHttpResponse {
732
755
  });
733
756
  }
734
757
  }
735
- else if (globalThis.Response && this.body instanceof Response /* Fetch Response */) {
758
+ else if (globalThis.Response &&
759
+ this.body instanceof Response /* Fetch Response */) {
736
760
  this.mergeFetchStatus(this.body.status);
737
761
  if (method === 'HEAD') {
738
762
  res.end();
@@ -791,42 +815,51 @@ function respondWithFetch(fetchBody, res) {
791
815
  });
792
816
  }
793
817
 
794
- const preStyles = 'font-family: monospace;'
795
- + 'width: 100%;'
796
- + 'max-width: 900px;'
797
- + 'padding: 10px;'
798
- + 'margin: 20px auto;'
799
- + 'border-radius: 8px;'
800
- + 'background-color: #494949;'
801
- + 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
818
+ const preStyles = 'font-family: monospace;' +
819
+ 'width: 100%;' +
820
+ 'max-width: 900px;' +
821
+ 'padding: 10px;' +
822
+ 'margin: 20px auto;' +
823
+ 'border-radius: 8px;' +
824
+ 'background-color: #494949;' +
825
+ 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
802
826
  class HttpErrorRenderer extends BaseHttpResponseRenderer {
803
827
  renderHtml(response) {
804
828
  const data = response.body || {};
805
829
  response.setContentType('text/html');
806
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
807
- return '<html style="background-color: #333; color: #bbb;">' +
830
+ const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
831
+ return ('<html style="background-color: #333; color: #bbb;">' +
808
832
  `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
809
833
  `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
810
834
  `<center><h4>${data.message}</h1></center><hr color="#666">` +
811
- `<center style="color: #666;"> Wooks v${"0.2.18"} </center>` +
812
- `${keys.length ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>` : ''}` +
813
- '</body></html>';
835
+ `<center style="color: #666;"> Wooks v${"0.2.20"} </center>` +
836
+ `${keys.length
837
+ ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>`
838
+ : ''}` +
839
+ '</body></html>');
814
840
  }
815
841
  renderText(response) {
816
842
  const data = response.body || {};
817
843
  response.setContentType('text/plain');
818
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
819
- return `${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}`
820
- + `\n\n${keys.length ? `${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}` : ''}`;
844
+ const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
845
+ return (`${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` +
846
+ `\n\n${keys.length
847
+ ? `${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}`
848
+ : ''}`);
821
849
  }
822
850
  renderJson(response) {
823
851
  const data = response.body || {};
824
852
  response.setContentType('application/json');
825
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
826
- return `{"statusCode":${escapeQuotes(data.statusCode)},`
827
- + `"error":"${escapeQuotes(data.error)}",`
828
- + `"message":"${escapeQuotes(data.message)}"`
829
- + `${keys.length ? (',' + keys.map(k => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(',')) : ''}}`;
853
+ const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
854
+ return (`{"statusCode":${escapeQuotes(data.statusCode)},` +
855
+ `"error":"${escapeQuotes(data.error)}",` +
856
+ `"message":"${escapeQuotes(data.message)}"` +
857
+ `${keys.length
858
+ ? ',' +
859
+ keys
860
+ .map((k) => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`)
861
+ .join(',')
862
+ : ''}}`);
830
863
  }
831
864
  render(response) {
832
865
  var _a;
@@ -847,7 +880,9 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
847
880
  }
848
881
  }
849
882
  function escapeQuotes(s) {
850
- return (typeof s === 'number' ? s : (s || '')).toString().replace(/[\""]/g, '\\"');
883
+ return (typeof s === 'number' ? s : s || '')
884
+ .toString()
885
+ .replace(/[\""]/g, '\\"');
851
886
  }
852
887
 
853
888
  class HttpError extends Error {
@@ -857,11 +892,13 @@ class HttpError extends Error {
857
892
  this._body = _body;
858
893
  }
859
894
  get body() {
860
- return typeof this._body === 'string' ? {
861
- statusCode: this.code,
862
- message: this.message,
863
- error: httpStatusCodes[this.code],
864
- } : Object.assign(Object.assign({}, this._body), { statusCode: this.code, message: this.message, error: httpStatusCodes[this.code] });
895
+ return typeof this._body === 'string'
896
+ ? {
897
+ statusCode: this.code,
898
+ message: this.message,
899
+ error: httpStatusCodes[this.code],
900
+ }
901
+ : Object.assign(Object.assign({}, this._body), { statusCode: this.code, message: this.message, error: httpStatusCodes[this.code] });
865
902
  }
866
903
  attachRenderer(renderer) {
867
904
  this.renderer = renderer;
@@ -938,7 +975,7 @@ class WooksHttp extends wooks.WooksAdapterBase {
938
975
  }
939
976
  listen(...args) {
940
977
  return __awaiter(this, void 0, void 0, function* () {
941
- const server = this.server = http.createServer(this.getServerCb());
978
+ const server = (this.server = http.createServer(this.getServerCb()));
942
979
  return new Promise((resolve, reject) => {
943
980
  server.once('listening', resolve);
944
981
  server.once('error', reject);
@@ -970,12 +1007,12 @@ class WooksHttp extends wooks.WooksAdapterBase {
970
1007
  }
971
1008
  getServerCb() {
972
1009
  return (req, res) => __awaiter(this, void 0, void 0, function* () {
973
- var _a;
1010
+ var _a, _b, _c;
974
1011
  const { restoreCtx, clearCtx } = createHttpContext({ req, res }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
975
1012
  const handlers = this.wooks.lookup(req.method, req.url);
976
- if (handlers) {
1013
+ if (handlers || ((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound)) {
977
1014
  try {
978
- yield this.processHandlers(handlers);
1015
+ yield this.processHandlers(handlers || [(_c = this.opts) === null || _c === void 0 ? void 0 : _c.onNotFound]);
979
1016
  }
980
1017
  catch (e) {
981
1018
  this.logger.error('Internal error, please report', e);
@@ -1010,7 +1047,7 @@ class WooksHttp extends wooks.WooksAdapterBase {
1010
1047
  break;
1011
1048
  }
1012
1049
  catch (e) {
1013
- this.logger.error(`Uncought route handler exception: ${(store('event').get('req').url || '')}`, e);
1050
+ this.logger.error(`Uncought route handler exception: ${store('event').get('req').url || ''}`, e);
1014
1051
  if (isLastHandler) {
1015
1052
  restoreCtx();
1016
1053
  this.respond(e);
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ import { TConsoleBase } from '@prostojs/logger';
9
9
  import { TEmpty } from '@wooksjs/event-core';
10
10
  import { TEventOptions } from '@wooksjs/event-core';
11
11
  import { TGenericContextStore } from '@wooksjs/event-core';
12
- import { TProstoRouterPathBuilder } from '@prostojs/router';
12
+ import { TProstoRouterPathHandle } from '@prostojs/router';
13
13
  import { TWooksHandler } from 'wooks';
14
14
  import { URLSearchParams as URLSearchParams_2 } from 'url';
15
15
  import { Wooks } from 'wooks';
@@ -349,6 +349,7 @@ export declare interface TWooksErrorBodyExt extends TWooksErrorBody {
349
349
  export declare interface TWooksHttpOptions {
350
350
  logger?: TConsoleBase;
351
351
  eventOptions?: TEventOptions;
352
+ onNotFound?: TWooksHandler<unknown>;
352
353
  }
353
354
 
354
355
  export declare interface TWooksResponseRenderer<T = unknown> {
@@ -488,14 +489,14 @@ export declare class WooksHttp extends WooksAdapterBase {
488
489
  protected opts?: TWooksHttpOptions | undefined;
489
490
  protected logger: TConsoleBase;
490
491
  constructor(opts?: TWooksHttpOptions | undefined, wooks?: Wooks | WooksAdapterBase);
491
- all<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
492
- get<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
493
- post<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
494
- put<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
495
- patch<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
496
- delete<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
497
- head<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
498
- options<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
492
+ all<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
493
+ get<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
494
+ post<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
495
+ put<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
496
+ patch<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
497
+ delete<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
498
+ head<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
499
+ options<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathHandle<ParamsType>;
499
500
  protected server?: Server;
500
501
  listen(...args: Parameters<Server['listen']>): Promise<unknown>;
501
502
  close(server?: Server): Promise<unknown>;
package/dist/index.mjs CHANGED
@@ -37,8 +37,11 @@ function useRequest() {
37
37
  const reqId = useEventId().getId;
38
38
  const forwardedIp = () => init('forwardedIp', () => {
39
39
  var _a;
40
- if (typeof req.headers[xForwardedFor] === 'string' && req.headers[xForwardedFor]) {
41
- return (_a = req.headers[xForwardedFor].split(',').shift()) === null || _a === void 0 ? void 0 : _a.trim();
40
+ if (typeof req.headers[xForwardedFor] === 'string' &&
41
+ req.headers[xForwardedFor]) {
42
+ return (_a = req.headers[xForwardedFor]
43
+ .split(',')
44
+ .shift()) === null || _a === void 0 ? void 0 : _a.trim();
42
45
  }
43
46
  else {
44
47
  return '';
@@ -56,8 +59,12 @@ function useRequest() {
56
59
  const getIpList = () => init('ipList', () => {
57
60
  var _a, _b;
58
61
  return {
59
- remoteIp: ((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress) || ((_b = req.connection) === null || _b === void 0 ? void 0 : _b.remoteAddress) || '',
60
- forwarded: (req.headers[xForwardedFor] || '').split(',').map(s => s.trim()),
62
+ remoteIp: ((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress) ||
63
+ ((_b = req.connection) === null || _b === void 0 ? void 0 : _b.remoteAddress) ||
64
+ '',
65
+ forwarded: (req.headers[xForwardedFor] || '')
66
+ .split(',')
67
+ .map((s) => s.trim()),
61
68
  };
62
69
  });
63
70
  return {
@@ -166,7 +173,7 @@ function convertTime(time, unit = 'ms') {
166
173
  const rg = /(\d+)(\w+)/g;
167
174
  let t = 0;
168
175
  let r;
169
- while (r = rg.exec(time)) {
176
+ while ((r = rg.exec(time))) {
170
177
  t += Number(r[1]) * (units[r[2]] || 0);
171
178
  }
172
179
  return t / units[unit];
@@ -204,9 +211,9 @@ function renderCacheControl(data) {
204
211
  const cacheControlFunc = {
205
212
  mustRevalidate: (v) => v ? 'must-revalidate' : '',
206
213
  noCache: (v) => v ? (typeof v === 'string' ? `no-cache="${v}"` : 'no-cache') : '',
207
- noStore: (v) => v ? 'no-store' : '',
208
- noTransform: (v) => v ? 'no-transform' : '',
209
- public: (v) => v ? 'public' : '',
214
+ noStore: (v) => (v ? 'no-store' : ''),
215
+ noTransform: (v) => (v ? 'no-transform' : ''),
216
+ public: (v) => (v ? 'public' : ''),
210
217
  private: (v) => v ? (typeof v === 'string' ? `private="${v}"` : 'private') : '',
211
218
  proxyRevalidate: (v) => v ? 'proxy-revalidate' : '',
212
219
  maxAge: (v) => 'max-age=' + convertTime(v, 's').toString(),
@@ -214,8 +221,10 @@ const cacheControlFunc = {
214
221
  };
215
222
 
216
223
  const renderAge = (v) => convertTime(v, 's').toString();
217
- const renderExpires = (v) => (typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString());
218
- const renderPragmaNoCache = (v) => v ? 'no-cache' : '';
224
+ const renderExpires = (v) => typeof v === 'string' || typeof v === 'number'
225
+ ? new Date(v).toUTCString()
226
+ : v.toUTCString();
227
+ const renderPragmaNoCache = (v) => (v ? 'no-cache' : '');
219
228
  // rfc7234#section-5.2.2
220
229
  function useSetCacheControl() {
221
230
  const { setHeader } = useSetHeaders();
@@ -246,7 +255,7 @@ function useResponse() {
246
255
  const responded = store('response').hook('responded');
247
256
  const statusCode = store('status').hook('code');
248
257
  function status(code) {
249
- return statusCode.value = code ? code : statusCode.value;
258
+ return (statusCode.value = code ? code : statusCode.value);
250
259
  }
251
260
  const rawResponse = (options) => {
252
261
  if (!options || !options.passthrough)
@@ -258,7 +267,7 @@ function useResponse() {
258
267
  hasResponded: () => responded.value || !res.writable || res.writableEnded,
259
268
  status: attachHook(status, {
260
269
  get: () => statusCode.value,
261
- set: (code) => statusCode.value = code,
270
+ set: (code) => (statusCode.value = code),
262
271
  }),
263
272
  };
264
273
  }
@@ -282,12 +291,15 @@ function renderCookie(key, data) {
282
291
  return `${key}=${encodeURIComponent(data.value)}${attrs}`;
283
292
  }
284
293
  const cookieAttrFunc = {
285
- expires: (v) => 'Expires=' + (typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString()),
294
+ expires: (v) => 'Expires=' +
295
+ (typeof v === 'string' || typeof v === 'number'
296
+ ? new Date(v).toUTCString()
297
+ : v.toUTCString()),
286
298
  maxAge: (v) => 'Max-Age=' + convertTime(v, 's').toString(),
287
299
  domain: (v) => 'Domain=' + v,
288
300
  path: (v) => 'Path=' + v,
289
- secure: (v) => v ? 'Secure' : '',
290
- httpOnly: (v) => v ? 'HttpOnly' : '',
301
+ secure: (v) => (v ? 'Secure' : ''),
302
+ httpOnly: (v) => (v ? 'HttpOnly' : ''),
291
303
  sameSite: (v) => v ? 'SameSite=' + (typeof v === 'string' ? v : 'Strict') : '',
292
304
  };
293
305
 
@@ -315,7 +327,9 @@ function useCookies() {
315
327
  const getCookie = (name) => init(name, () => {
316
328
  if (cookie) {
317
329
  const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, 'i').exec(cookie);
318
- return result && result[1] ? safeDecodeURIComponent(result[1]) : null;
330
+ return result && result[1]
331
+ ? safeDecodeURIComponent(result[1])
332
+ : null;
319
333
  }
320
334
  else {
321
335
  return null;
@@ -336,7 +350,10 @@ function useSetCookies() {
336
350
  });
337
351
  }
338
352
  function cookies() {
339
- return cookiesStore.entries().filter(a => !!a[1]).map(([key, value]) => renderCookie(key, value));
353
+ return cookiesStore
354
+ .entries()
355
+ .filter((a) => !!a[1])
356
+ .map(([key, value]) => renderCookie(key, value));
340
357
  }
341
358
  return {
342
359
  setCookie,
@@ -366,7 +383,7 @@ class WooksURLSearchParams extends URLSearchParams {
366
383
  const json = {};
367
384
  for (const [key, value] of this.entries()) {
368
385
  if (isArrayParam(key)) {
369
- const a = json[key] = (json[key] || []);
386
+ const a = (json[key] = (json[key] || []));
370
387
  a.push(value);
371
388
  }
372
389
  else {
@@ -410,6 +427,8 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
410
427
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
411
428
  PERFORMANCE OF THIS SOFTWARE.
412
429
  ***************************************************************************** */
430
+ /* global Reflect, Promise */
431
+
413
432
 
414
433
  function __awaiter(thisArg, _arguments, P, generator) {
415
434
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -443,7 +462,9 @@ function __asyncValues(o) {
443
462
 
444
463
  class BaseHttpResponseRenderer {
445
464
  render(response) {
446
- if (typeof response.body === 'string' || typeof response.body === 'boolean' || typeof response.body === 'number') {
465
+ if (typeof response.body === 'string' ||
466
+ typeof response.body === 'boolean' ||
467
+ typeof response.body === 'number') {
447
468
  if (!response.getContentType())
448
469
  response.setContentType('text/plain');
449
470
  return response.body.toString();
@@ -641,7 +662,7 @@ class BaseHttpResponse {
641
662
  return this;
642
663
  }
643
664
  setCookie(name, value, attrs) {
644
- const cookies = this._headers['set-cookie'] = (this._headers['set-cookie'] || []);
665
+ const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
645
666
  cookies.push(renderCookie(name, { value, attrs: attrs || {} }));
646
667
  return this;
647
668
  }
@@ -649,7 +670,7 @@ class BaseHttpResponse {
649
670
  this.setHeader('cache-control', renderCacheControl(data));
650
671
  }
651
672
  setCookieRaw(rawValue) {
652
- const cookies = this._headers['set-cookie'] = (this._headers['set-cookie'] || []);
673
+ const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
653
674
  cookies.push(rawValue);
654
675
  return this;
655
676
  }
@@ -666,7 +687,7 @@ class BaseHttpResponse {
666
687
  mergeHeaders() {
667
688
  const { headers } = useSetHeaders();
668
689
  const { cookies, removeCookie } = useSetCookies();
669
- const newCookies = (this._headers['set-cookie'] || []);
690
+ const newCookies = this._headers['set-cookie'] || [];
670
691
  for (const cookie of newCookies) {
671
692
  removeCookie(cookie.slice(0, cookie.indexOf('=')));
672
693
  }
@@ -681,7 +702,9 @@ class BaseHttpResponse {
681
702
  this.status = this.status || useResponse().status();
682
703
  if (!this.status) {
683
704
  const { method } = useRequest();
684
- this.status = renderedBody ? defaultStatus[method] || EHttpStatusCode.OK : EHttpStatusCode.NoContent;
705
+ this.status = renderedBody
706
+ ? defaultStatus[method] || EHttpStatusCode.OK
707
+ : EHttpStatusCode.NoContent;
685
708
  }
686
709
  return this;
687
710
  }
@@ -730,7 +753,8 @@ class BaseHttpResponse {
730
753
  });
731
754
  }
732
755
  }
733
- else if (globalThis.Response && this.body instanceof Response /* Fetch Response */) {
756
+ else if (globalThis.Response &&
757
+ this.body instanceof Response /* Fetch Response */) {
734
758
  this.mergeFetchStatus(this.body.status);
735
759
  if (method === 'HEAD') {
736
760
  res.end();
@@ -789,42 +813,51 @@ function respondWithFetch(fetchBody, res) {
789
813
  });
790
814
  }
791
815
 
792
- const preStyles = 'font-family: monospace;'
793
- + 'width: 100%;'
794
- + 'max-width: 900px;'
795
- + 'padding: 10px;'
796
- + 'margin: 20px auto;'
797
- + 'border-radius: 8px;'
798
- + 'background-color: #494949;'
799
- + 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
816
+ const preStyles = 'font-family: monospace;' +
817
+ 'width: 100%;' +
818
+ 'max-width: 900px;' +
819
+ 'padding: 10px;' +
820
+ 'margin: 20px auto;' +
821
+ 'border-radius: 8px;' +
822
+ 'background-color: #494949;' +
823
+ 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
800
824
  class HttpErrorRenderer extends BaseHttpResponseRenderer {
801
825
  renderHtml(response) {
802
826
  const data = response.body || {};
803
827
  response.setContentType('text/html');
804
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
805
- return '<html style="background-color: #333; color: #bbb;">' +
828
+ const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
829
+ return ('<html style="background-color: #333; color: #bbb;">' +
806
830
  `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
807
831
  `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
808
832
  `<center><h4>${data.message}</h1></center><hr color="#666">` +
809
- `<center style="color: #666;"> Wooks v${"0.2.18"} </center>` +
810
- `${keys.length ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>` : ''}` +
811
- '</body></html>';
833
+ `<center style="color: #666;"> Wooks v${"0.2.20"} </center>` +
834
+ `${keys.length
835
+ ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>`
836
+ : ''}` +
837
+ '</body></html>');
812
838
  }
813
839
  renderText(response) {
814
840
  const data = response.body || {};
815
841
  response.setContentType('text/plain');
816
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
817
- return `${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}`
818
- + `\n\n${keys.length ? `${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}` : ''}`;
842
+ const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
843
+ return (`${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` +
844
+ `\n\n${keys.length
845
+ ? `${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}`
846
+ : ''}`);
819
847
  }
820
848
  renderJson(response) {
821
849
  const data = response.body || {};
822
850
  response.setContentType('application/json');
823
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
824
- return `{"statusCode":${escapeQuotes(data.statusCode)},`
825
- + `"error":"${escapeQuotes(data.error)}",`
826
- + `"message":"${escapeQuotes(data.message)}"`
827
- + `${keys.length ? (',' + keys.map(k => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(',')) : ''}}`;
851
+ const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
852
+ return (`{"statusCode":${escapeQuotes(data.statusCode)},` +
853
+ `"error":"${escapeQuotes(data.error)}",` +
854
+ `"message":"${escapeQuotes(data.message)}"` +
855
+ `${keys.length
856
+ ? ',' +
857
+ keys
858
+ .map((k) => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`)
859
+ .join(',')
860
+ : ''}}`);
828
861
  }
829
862
  render(response) {
830
863
  var _a;
@@ -845,7 +878,9 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
845
878
  }
846
879
  }
847
880
  function escapeQuotes(s) {
848
- return (typeof s === 'number' ? s : (s || '')).toString().replace(/[\""]/g, '\\"');
881
+ return (typeof s === 'number' ? s : s || '')
882
+ .toString()
883
+ .replace(/[\""]/g, '\\"');
849
884
  }
850
885
 
851
886
  class HttpError extends Error {
@@ -855,11 +890,13 @@ class HttpError extends Error {
855
890
  this._body = _body;
856
891
  }
857
892
  get body() {
858
- return typeof this._body === 'string' ? {
859
- statusCode: this.code,
860
- message: this.message,
861
- error: httpStatusCodes[this.code],
862
- } : Object.assign(Object.assign({}, this._body), { statusCode: this.code, message: this.message, error: httpStatusCodes[this.code] });
893
+ return typeof this._body === 'string'
894
+ ? {
895
+ statusCode: this.code,
896
+ message: this.message,
897
+ error: httpStatusCodes[this.code],
898
+ }
899
+ : Object.assign(Object.assign({}, this._body), { statusCode: this.code, message: this.message, error: httpStatusCodes[this.code] });
863
900
  }
864
901
  attachRenderer(renderer) {
865
902
  this.renderer = renderer;
@@ -936,7 +973,7 @@ class WooksHttp extends WooksAdapterBase {
936
973
  }
937
974
  listen(...args) {
938
975
  return __awaiter(this, void 0, void 0, function* () {
939
- const server = this.server = http.createServer(this.getServerCb());
976
+ const server = (this.server = http.createServer(this.getServerCb()));
940
977
  return new Promise((resolve, reject) => {
941
978
  server.once('listening', resolve);
942
979
  server.once('error', reject);
@@ -968,12 +1005,12 @@ class WooksHttp extends WooksAdapterBase {
968
1005
  }
969
1006
  getServerCb() {
970
1007
  return (req, res) => __awaiter(this, void 0, void 0, function* () {
971
- var _a;
1008
+ var _a, _b, _c;
972
1009
  const { restoreCtx, clearCtx } = createHttpContext({ req, res }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
973
1010
  const handlers = this.wooks.lookup(req.method, req.url);
974
- if (handlers) {
1011
+ if (handlers || ((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound)) {
975
1012
  try {
976
- yield this.processHandlers(handlers);
1013
+ yield this.processHandlers(handlers || [(_c = this.opts) === null || _c === void 0 ? void 0 : _c.onNotFound]);
977
1014
  }
978
1015
  catch (e) {
979
1016
  this.logger.error('Internal error, please report', e);
@@ -1008,7 +1045,7 @@ class WooksHttp extends WooksAdapterBase {
1008
1045
  break;
1009
1046
  }
1010
1047
  catch (e) {
1011
- this.logger.error(`Uncought route handler exception: ${(store('event').get('req').url || '')}`, e);
1048
+ this.logger.error(`Uncought route handler exception: ${store('event').get('req').url || ''}`, e);
1012
1049
  if (isLastHandler) {
1013
1050
  restoreCtx();
1014
1051
  this.respond(e);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooksjs/event-http",
3
- "version": "0.2.18",
3
+ "version": "0.2.20",
4
4
  "description": "@wooksjs/event-http",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -31,12 +31,12 @@
31
31
  "url": "https://github.com/wooksjs/wooksjs/issues"
32
32
  },
33
33
  "peerDependencies": {
34
- "wooks": "0.2.18",
35
- "@prostojs/router": "^0.0.16",
36
- "@wooksjs/event-core": "0.2.18"
34
+ "wooks": "0.2.20",
35
+ "@prostojs/router": "^0.1.0",
36
+ "@wooksjs/event-core": "0.2.20"
37
37
  },
38
38
  "dependencies": {
39
- "@prostojs/logger": "^0.3.4"
39
+ "@prostojs/logger": "^0.3.6"
40
40
  },
41
41
  "homepage": "https://github.com/wooksjs/wooksjs/tree/main/packages/event-http#readme"
42
42
  }