barejs 0.1.48 → 0.1.50

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/src/core/bare.ts CHANGED
@@ -5,6 +5,14 @@ import { Type as typebox, Type as t } from '@sinclair/typebox';
5
5
  import { join } from "node:path";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { bootstrapConfig } from "./loader";
8
+ import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
9
+
10
+ export interface WebSocketRouteHandler {
11
+ open?: (ws: any) => void;
12
+ message?: (ws: any, message: string | Buffer) => void;
13
+ close?: (ws: any, code: number, reason: string) => void;
14
+ drain?: (ws: any) => void;
15
+ }
8
16
 
9
17
  export interface NotFoundResponse {
10
18
  status: number;
@@ -19,10 +27,48 @@ export class BareJS extends BareRouter {
19
27
  private compiled = false;
20
28
  private poolMask: number;
21
29
  private _useLog: boolean = false;
30
+ private errorHandler?: (err: any, ctx: Context) => any;
31
+ private wsRoutes = new Map<string, WebSocketRouteHandler>();
32
+ private startHooks: (() => void | Promise<void>)[] = [];
33
+ private stopHooks: (() => void | Promise<void>)[] = [];
34
+ private server?: ReturnType<typeof Bun.serve>;
35
+ private shutdownHandler?: () => Promise<void>;
36
+ private wsAdapter = {
37
+ open(ws: any) { ws.data?.open?.(ws); },
38
+ message(ws: any, msg: any) { ws.data?.message?.(ws, msg); },
39
+ close(ws: any, code: any, reason: any) { ws.data?.close?.(ws, code, reason); },
40
+ drain(ws: any) { ws.data?.drain?.(ws); }
41
+ };
42
+
22
43
  public useLog(enabled: boolean = true): this {
23
44
  this._useLog = enabled;
24
45
  return this;
25
46
  }
47
+
48
+ public onStart(fn: () => void | Promise<void>): this {
49
+ this.startHooks.push(fn);
50
+ return this;
51
+ }
52
+
53
+ public onStop(fn: () => void | Promise<void>): this {
54
+ this.stopHooks.push(fn);
55
+ return this;
56
+ }
57
+
58
+ public async stop(closeActiveConnections = false): Promise<void> {
59
+ if (this.shutdownHandler) {
60
+ process.off("SIGINT", this.shutdownHandler);
61
+ process.off("SIGTERM", this.shutdownHandler);
62
+ this.shutdownHandler = undefined;
63
+ }
64
+ if (this.server) {
65
+ this.server.stop(closeActiveConnections);
66
+ this.server = undefined;
67
+ }
68
+ for (const hook of this.stopHooks) {
69
+ await hook();
70
+ }
71
+ }
26
72
  constructor(poolSize: number = 1024) {
27
73
  super();
28
74
  bootstrapConfig();
@@ -53,11 +99,136 @@ export class BareJS extends BareRouter {
53
99
  this.notFoundHandler = handler;
54
100
  }
55
101
 
102
+ public onError(handler: (err: any, ctx: Context) => any): this {
103
+ this.errorHandler = handler;
104
+ return this;
105
+ }
106
+
107
+ public ws(path: string, handler: WebSocketRouteHandler): this {
108
+ const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
109
+ this.wsRoutes.set(normalized, handler);
110
+ return this;
111
+ }
112
+
113
+ public docs(path: string = '/docs', options: OpenAPIOptions = {}): this {
114
+ const basePath = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/docs';
115
+ const jsonPath = `${basePath}/json`;
116
+ let cachedSpec: string | null = null;
117
+ const html = renderDocsHTML(jsonPath, options.title || `${this.name} API Docs`);
118
+
119
+ this.get(jsonPath, () => {
120
+ if (!cachedSpec) {
121
+ cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, ...options }));
122
+ }
123
+ return new Response(cachedSpec, {
124
+ status: 200,
125
+ headers: { 'content-type': 'application/json' }
126
+ });
127
+ });
128
+
129
+ this.get(basePath, () => {
130
+ return new Response(html, {
131
+ status: 200,
132
+ headers: { 'content-type': 'text/html; charset=utf-8' }
133
+ });
134
+ });
135
+
136
+ return this;
137
+ }
138
+
139
+ public rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this {
140
+ const execCall = async (reqObj: any, ctx: Context) => {
141
+ if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
142
+ return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: reqObj?.id ?? null };
143
+ }
144
+ const fn = Object.hasOwn(procedures, reqObj.method) ? procedures[reqObj.method] : undefined;
145
+ if (!fn) {
146
+ return { jsonrpc: '2.0', error: { code: -32601, message: 'Method not found' }, id: reqObj.id ?? null };
147
+ }
148
+ try {
149
+ const result = await fn(reqObj.params, ctx);
150
+ if (reqObj.id === undefined) return null; // Notification
151
+ return { jsonrpc: '2.0', result, id: reqObj.id };
152
+ } catch (err: any) {
153
+ return {
154
+ jsonrpc: '2.0',
155
+ error: { code: -32603, message: err?.message || 'Internal error' },
156
+ id: reqObj.id ?? null
157
+ };
158
+ }
159
+ };
160
+
161
+ this.post(path, async (ctx: Context) => {
162
+ const payload = await ctx.jsonBody();
163
+ if (!payload) {
164
+ return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
165
+ }
166
+ if (Array.isArray(payload)) {
167
+ if (payload.length === 0) {
168
+ return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null });
169
+ }
170
+ const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
171
+ return results.length > 0 ? results : new Response(null, { status: 204 });
172
+ }
173
+ const res = await execCall(payload, ctx);
174
+ return res === null ? new Response(null, { status: 204 }) : res;
175
+ });
176
+
177
+ return this;
178
+ }
179
+
180
+
181
+ private _hasDerive = false;
182
+ public derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T): this {
183
+ this._hasDerive = true;
184
+ this.use(async (ctx: any, next: any) => {
185
+ const derived = await fn(ctx);
186
+ if (derived && typeof derived === 'object') {
187
+ const keys = Object.keys(derived);
188
+ if (!ctx._derivedKeys) ctx._derivedKeys = [];
189
+ for (let i = 0; i < keys.length; i++) {
190
+ const k = keys[i]!;
191
+ if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
192
+ ctx[k] = (derived as any)[k];
193
+ ctx._derivedKeys.push(k);
194
+ }
195
+ }
196
+ }
197
+ return next();
198
+ });
199
+ return this;
200
+ }
56
201
 
57
202
  // inherited use() from BareRouter handles router merging now
58
203
 
59
204
  private compileHandler(pipeline: any[], isLog: boolean): Function {
205
+ const timeoutMw = pipeline.find((fn) => fn?.__timeout);
206
+ if (timeoutMw) {
207
+ const { ms, status, message } = timeoutMw.__timeout;
208
+ const innerPipeline = pipeline.filter((fn) => !fn?.__timeout);
209
+ const innerCompiled = this.compileHandler(innerPipeline, isLog);
210
+ return async (ctx: Context, doLog?: any) => {
211
+ const res = innerCompiled(ctx, doLog);
212
+ if (!res || !res.then) return res;
213
+ let timer: ReturnType<typeof setTimeout> | undefined;
214
+ try {
215
+ const timeoutPromise = new Promise<Response>((resolve) => {
216
+ timer = setTimeout(() => {
217
+ resolve(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }));
218
+ }, ms);
219
+ });
220
+ return await Promise.race([res, timeoutPromise]);
221
+ } finally {
222
+ if (timer !== undefined) clearTimeout(timer);
223
+ }
224
+ };
225
+ }
226
+
60
227
  const len = pipeline.length;
228
+ const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
229
+ const rFilter = rFilterMw?.__responseFilter;
230
+ const idemMw = pipeline.find((fn) => fn?.__idempotencyCommit);
231
+ const idemCommit = idemMw?.__idempotencyCommit;
61
232
 
62
233
  // Static ResponseInit for 200 OK (Zero Allocation)
63
234
  const json200 = { status: 200, headers: { "content-type": "application/json" } };
@@ -68,33 +239,59 @@ export class BareJS extends BareRouter {
68
239
 
69
240
  // Inline Finalizer
70
241
  const finalizeCode = `
242
+ ${rFilter ? 'res = rFilter(res);' : ''}
71
243
  if (res instanceof Response) {
244
+ if (ctx._headers) {
245
+ for (const k in ctx._headers) {
246
+ if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
247
+ }
248
+ }
249
+ if (ctx._setCookies) {
250
+ for (let i = 0; i < ctx._setCookies.length; i++) res.headers.append('Set-Cookie', ctx._setCookies[i]);
251
+ }
72
252
  ${logResCode}
73
253
  return res;
74
254
  }
75
255
 
76
256
  const finalStatus = ctx._status || 200;
257
+ ${idemCommit ? 'idemCommit(ctx, res, finalStatus);' : ''}
77
258
  ${logStatusCode}
78
259
 
260
+ let outRes;
79
261
  if (typeof res === 'string') {
80
- if (finalStatus === 200 && !ctx._headers) return new Response(res, text200);
81
- return new Response(res, {
262
+ if (finalStatus === 200 && !ctx._headers) {
263
+ outRes = new Response(res, text200);
264
+ } else {
265
+ outRes = new Response(res, {
266
+ status: finalStatus,
267
+ headers: ctx._headers || text200.headers
268
+ });
269
+ }
270
+ } else if (finalStatus === 200 && !ctx._headers) {
271
+ outRes = Response.json(res ?? null, json200);
272
+ } else {
273
+ outRes = Response.json(res ?? null, {
82
274
  status: finalStatus,
83
- headers: ctx._headers || text200.headers
275
+ headers: ctx._headers || json200.headers
84
276
  });
85
277
  }
86
-
87
- if (finalStatus === 200 && !ctx._headers) return Response.json(res ?? null, json200);
88
- return Response.json(res ?? null, {
89
- status: finalStatus,
90
- headers: ctx._headers && ctx._headers["content-type"] ? ctx._headers : json200.headers
91
- });
278
+
279
+ if (ctx._setCookies) {
280
+ for (let i = 0; i < ctx._setCookies.length; i++) outRes.headers.append('Set-Cookie', ctx._setCookies[i]);
281
+ }
282
+ return outRes;
92
283
  `;
93
284
 
94
285
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
95
286
 
96
287
  if (len === 1) {
97
- const fn0 = pipeline[0];
288
+ const fn0 = pipeline[0]!;
289
+ if (fn0.constructor.name === 'AsyncFunction') {
290
+ return new Function('fn0', 'json200', 'text200', `return async function(${argSig}) {
291
+ const res = await fn0(ctx);
292
+ ${finalizeCode}
293
+ }`)(fn0, json200, text200);
294
+ }
98
295
  return new Function('fn0', 'json200', 'text200', `return function(${argSig}) {
99
296
  const res = fn0(ctx);
100
297
  if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
@@ -128,8 +325,8 @@ export class BareJS extends BareRouter {
128
325
  code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
129
326
  }
130
327
  code += `
131
- const res = fn${len - 1}(ctx);
132
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
328
+ let res = fn${len - 1}(ctx);
329
+ if (res && res.then) return res.then(v => { let res = v; ${finalizeCode} });
133
330
  ${finalizeCode}
134
331
  `;
135
332
  }
@@ -139,7 +336,7 @@ export class BareJS extends BareRouter {
139
336
  ? `return async function(${argSig})`
140
337
  : `return function(${argSig})`;
141
338
 
142
- return new Function(...fnNames, 'noop', 'json200', 'text200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200);
339
+ return new Function(...fnNames, 'noop', 'json200', 'text200', ...(rFilter ? ['rFilter'] : []), ...(idemCommit ? ['idemCommit'] : []), `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...(rFilter ? [rFilter] : []), ...(idemCommit ? [idemCommit] : []));
143
340
  }
144
341
 
145
342
  public compile() {
@@ -153,11 +350,27 @@ export class BareJS extends BareRouter {
153
350
  const pool = this.pool;
154
351
  const maxPool = pool.length;
155
352
  const hNotFound = this.notFoundHandler;
156
- const hError = (err: any) => ({
157
- status: 500,
158
- message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
159
- stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
160
- });
353
+ const customError = this.errorHandler;
354
+ const hError = (err: any, ctx: Context) => {
355
+ if (customError) {
356
+ const res = customError(err, ctx);
357
+ if (res instanceof Response) return res;
358
+ const status = ctx._status >= 400 ? ctx._status : 500;
359
+ if (typeof res === 'string') return new Response(res, { status });
360
+ return Response.json(res ?? null, { status });
361
+ }
362
+ if (err?.status >= 400 && err?.status < 500) {
363
+ return Response.json({
364
+ status: err.status,
365
+ message: err.message || 'Bad Request'
366
+ }, { status: err.status });
367
+ }
368
+ return Response.json({
369
+ status: 500,
370
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
371
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
372
+ }, { status: 500 });
373
+ };
161
374
 
162
375
  const hoistedHandlers: Function[] = [];
163
376
  const register = (h: Function) => {
@@ -170,11 +383,26 @@ export class BareJS extends BareRouter {
170
383
  const EMPTY_PARAMS = Object.freeze({});
171
384
  const hNames = hoistedHandlers.map((_, i) => `h${i}`);
172
385
 
386
+ const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit));
387
+ const deriveCleanup = this._hasDerive
388
+ ? `if (ctx._derivedKeys) { for (let i = 0; i < ctx._derivedKeys.length; i++) delete ctx[ctx._derivedKeys[i]]; ctx._derivedKeys = undefined; }`
389
+ : '';
390
+ const idemCleanup = hasIdem
391
+ ? `if (ctx._idempotencyKey) { ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
392
+ : '';
393
+
173
394
  const releaseCode = `
174
395
  if (ctx.store.size > 0) ctx.store.clear();
396
+ ${deriveCleanup}
397
+ ${idemCleanup}
175
398
  ctx.req = undefined;
399
+ ctx._status = 200;
176
400
  ctx.body = undefined;
401
+ ctx._query = undefined;
402
+ ctx._cookies = undefined;
403
+ ctx._setCookies = undefined;
177
404
  ctx._headers = undefined;
405
+ ctx._requestId = undefined;
178
406
  ctx.params = EMPTY_PARAMS;
179
407
  if (poolTop < maxPool) pool[poolTop++] = ctx;
180
408
  `;
@@ -182,14 +410,67 @@ export class BareJS extends BareRouter {
182
410
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
183
411
  const routerCode = rawRouterCode.replace(
184
412
  /return (h\d+)\(ctx\);/g,
185
- `const out = $1${callSuffix};
186
- if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${releaseCode} ${isLog ? 'doLog(500);' : ''} return Response.json(hError(e), { status: 500 }); });
413
+ `out = $1${callSuffix};
414
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { const errRes = hError(e, ctx); ${releaseCode} ${isLog ? 'doLog(errRes.status || 500);' : ''} return errRes; });
187
415
  ${releaseCode}
188
416
  return out;`
189
417
  );
190
418
 
191
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...hNames];
192
- const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...hoistedHandlers];
419
+ const hasGlobalMw = this.groupMiddleware.length > 0;
420
+ const hOptions = hasGlobalMw ? this.compileHandler(this.groupMiddleware, isLog) : undefined;
421
+ const optionsFallback = hasGlobalMw
422
+ ? `if (method === 'OPTIONS') {
423
+ out = hOptions${callSuffix};
424
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { const errRes = hError(e, ctx); ${releaseCode} ${isLog ? 'doLog(errRes.status || 500);' : ''} return errRes; });
425
+ ${releaseCode}
426
+ return out;
427
+ }`
428
+ : '';
429
+
430
+ const staticMws = this.groupMiddleware.filter((m: any) => m.__isStatic);
431
+ const hasStaticMw = staticMws.length > 0;
432
+ const runStatic = hasStaticMw
433
+ ? async (ctx: Context) => {
434
+ const noop = () => {};
435
+ for (let i = 0; i < staticMws.length; i++) {
436
+ const r = await staticMws[i](ctx, noop);
437
+ if (r instanceof Response) {
438
+ if (ctx._headers) {
439
+ for (const k in ctx._headers) {
440
+ const val = ctx._headers[k];
441
+ if (val !== undefined && !r.headers.has(k)) r.headers.set(k, val);
442
+ }
443
+ }
444
+ return r;
445
+ }
446
+ }
447
+ return undefined;
448
+ }
449
+ : undefined;
450
+
451
+ const staticFallback = hasStaticMw
452
+ ? `if (method === 'GET' || method === 'HEAD') {
453
+ out = runStatic(ctx);
454
+ if (out && out.then) {
455
+ return out.then((v) => {
456
+ if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
457
+ const errorBody = hNotFound();
458
+ const status = errorBody.status || 404;
459
+ ${isLog ? 'doLog(status);' : ''}
460
+ ${releaseCode}
461
+ return Response.json(errorBody, { status });
462
+ }, (e) => {
463
+ const errRes = hError(e, ctx);
464
+ ${releaseCode}
465
+ ${isLog ? 'doLog(errRes.status || 500);' : ''}
466
+ return errRes;
467
+ });
468
+ }
469
+ }`
470
+ : '';
471
+
472
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
473
+ const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
193
474
 
194
475
  const logInit = isLog ? `
195
476
  const start = performance.now();
@@ -216,18 +497,18 @@ export class BareJS extends BareRouter {
216
497
 
217
498
  const method = req.method;
218
499
  const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
500
+ let out;
219
501
  ${logInit}
220
502
 
221
503
  try {
222
504
  ctx.req = req;
223
- ctx._status = 200;
224
- ctx._headers = undefined;
225
- if (ctx.store.size > 0) ctx.store.clear();
226
- ctx.params = EMPTY_PARAMS;
227
- ctx.body = undefined;
228
505
 
229
506
  ${routerCode}
230
507
 
508
+ ${optionsFallback}
509
+
510
+ ${staticFallback}
511
+
231
512
  const errorBody = hNotFound();
232
513
  const status = errorBody.status || 404;
233
514
  ${isLog ? 'doLog(status);' : ''}
@@ -235,9 +516,10 @@ export class BareJS extends BareRouter {
235
516
  return Response.json(errorBody, { status });
236
517
 
237
518
  } catch (e) {
238
- ${isLog ? 'doLog(500);' : ''}
519
+ const errRes = hError(e, ctx);
520
+ ${isLog ? 'doLog(errRes.status || 500);' : ''}
239
521
  ${releaseCode}
240
- return Response.json(hError(e), { status: 500 });
522
+ return errRes;
241
523
  }
242
524
  }
243
525
  `;
@@ -280,35 +562,65 @@ export class BareJS extends BareRouter {
280
562
  `);
281
563
  }
282
564
 
283
- const server = Bun.serve({
284
- port: finalPort,
285
- hostname,
286
- fetch: this.fetch,
287
- reusePort: reusePort,
288
- });
565
+ const wsRoutes = this.wsRoutes;
566
+ const baseFetch = this.fetch;
567
+ const hasWs = wsRoutes.size > 0;
568
+
569
+ const server = hasWs
570
+ ? Bun.serve<WebSocketRouteHandler>({
571
+ port: finalPort,
572
+ hostname,
573
+ reusePort,
574
+ fetch(req: Request, srv: any) {
575
+ if (req.headers.get('upgrade') === 'websocket') {
576
+ const url = req.url;
577
+ const s = url.indexOf('/', 8);
578
+ const q = s === -1 ? -1 : url.indexOf('?', s);
579
+ const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
580
+ const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
581
+ const handler = wsRoutes.get(normalized);
582
+ if (handler && srv.upgrade(req, { data: handler })) {
583
+ return undefined as any;
584
+ }
585
+ }
586
+ return baseFetch(req);
587
+ },
588
+ websocket: this.wsAdapter
589
+ })
590
+ : Bun.serve({
591
+ port: finalPort,
592
+ hostname,
593
+ reusePort,
594
+ fetch: baseFetch
595
+ });
289
596
 
290
- const shutdown = () => {
597
+ this.server = server;
598
+ for (const hook of this.startHooks) {
599
+ Promise.resolve(hook()).catch((e) => console.error(`[${this.name}] onStart error:`, e));
600
+ }
601
+
602
+ const shutdown = async () => {
291
603
  const isProd = process.env.NODE_ENV === 'production';
292
604
  const serverName = this.name;
293
605
  const supportsEmoji = process.stdout.isTTY;
294
606
 
295
607
  if (isProd) {
296
608
  console.log(`[${serverName}] INFO: Stopping server...`);
609
+ await this.stop(false);
297
610
  } else {
298
-
299
611
  const stopIcon = supportsEmoji ? "🛑" : "!";
300
612
  const checkIcon = supportsEmoji ? "✅" : "v";
301
-
302
-
303
613
  process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
304
- server.stop();
614
+ await this.stop(false);
305
615
  process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
306
616
  }
307
617
  process.exit(0);
308
618
  };
309
619
 
620
+ this.shutdownHandler = shutdown;
310
621
  process.on("SIGINT", shutdown);
311
622
  process.on("SIGTERM", shutdown);
623
+ return server;
312
624
  }
313
625
  }
314
626