-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
458 lines (425 loc) · 15.1 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import * as net from 'net';
import * as http from 'http';
import * as https from "https";
import * as http2 from "http2";
import * as cookies from './middlewares/cookies';
import * as session from './middlewares/session';
import * as pathToRegex from "./util/pathToRegex";
declare namespace App {
export interface Context {
/**
* if `init({protocol: 'http2'})`
* then [[Http2ServerRequest]]
* else [[IncomingMessage]]
*/
request: http.IncomingMessage | http2.Http2ServerRequest;
/**
* if `init({protocol: 'http2'})`
* then [[Http2ServerResponse]]
* else [[ServerResponse]]
*/
response: http.ServerResponse | http2.Http2ServerResponse;
/**
* params from url
*
* @example
* ```js
* app.get('/:username/:commentId', ({params}) => params))
* ```
*
* When you call it :
* ```
* HTTP GET /tpoisseau/1
* {"username": "tpoisseau", "commentId": 1}
* ```
*/
params: { [key: string]: string };
/**
* provided when
*
* ```js
* import {parseCookie} from 'u-http-server';
*
* app.use(app.parseCookie);
*
* app.get('/', ({cookies}) => cookies);
* ```
*
* When you call it :
* ```
* HTTP GET /
* {}
*
* // a json object with cookies info
* ```
*/
cookies?: object;
/**
* provided when
*
* ```js
* import {sessionInMemory} from 'u-http-server';
*
* app.use(app.sessionInMemory);
* app.use(ctx => ctx.session.lastVisitedUrl = app.address + ctx.request.url)
*
* app.get('/session-info', ({session}) => session);
* ```
*
* When you call it :
* ```
* HTTP GET /
* {"lastVisitedUrl": "http://localhost:3000/session-info"}
* ```
*/
session?: object;
/**
* Provided by custom middlewares
*
* All middlewares (and routes) can edit the context, be carefull to not clash with other middlewares 😉
*/
[key: string]: any;
}
/**
* Your callback middleware will be called with ctx and lastResult.
*
* Will be `await` by the request handler and use the resolved result as `lastResult` for the next middleware call
*/
export type Middleware = (ctx: Context, lastResult?: any) => Promise<any>
/**
* It's for internal use only
*
* `.use(` and `.route(` generate a [[MiddlewareItem]] and push it in appropriate stack.
*
* Request handler iterate on this stacks, use [[MiddlewareItem.methods]] and [[MiddlewareItem.route]]
* to check if request match. If it match call [[MiddlewareItem.middleware]]
*/
export interface MiddlewareItem {
methods: string[];
route: pathToRegex.Return;
middleware: Middleware;
}
/**
* @see https://nodejs.org/api/http.html#http_event_clienterror
*/
export interface ClientError extends Error {
bytesParsed: number;
rawPacket: Buffer;
}
/**
* For complete available options :
*
* Base [[InitOptions]]:
* - [[InitOptions.protocol]]
* - [[InitOptions.selfSigned]]
* - [[InitOptions.http2Secure]]
*
* Others options are shared between [[ServerOptions]] and [[SecureServerOptions]]
*
* If you need use your own ssl certificates :
* - [[InitOptions.key]] - your private key
* - [[InitOptions.cert]] - the certificate
*
* You can eventually need to :
* - [[InitOptions.ca]] - Certificate Authority
* - [[InitOptions.pfx]] - replace [[InitOptions.key]] and [[InitOptions.cert]].
* - [[InitOptions.passphrase]] - if your private key is with it
*
* @see https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener
* @see https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener
* @see https://nodejs.org/api/http2.html#http2_http2_createserver_options_onrequesthandler
* @see https://nodejs.org/api/http2.html#http2_http2_createsecureserver_options_onrequesthandler
*/
export interface InitOptions extends http.ServerOptions, http2.SecureServerOptions {
/**
* The server protocol
* @default 'http'
* */
protocol?: 'http' | 'https' | 'http2';
/**
* Set to true if you want a self signed ssl certificate
* Generated for runtime.
*
* @default false
* */
selfSigned?: boolean;
/**
* If you use http2 protocol
* You should choose between a server with or without TLS layer
*
* Disable it is highly discouraged because majority of navigator disallow http2 without a secure layer
*
* @default true
* */
http2Secure?: boolean;
}
/**
* It's for internal use only
*
* private `_use(` method support the overloading and normalyze it into the complete signature.
*/
export type ReturnPUse = [string[], pathToRegex.Return, Middleware];
/**
* A route can be either :
* - a string, will be normalized by [[pathToRegex]]
* - a RegExp, will be normalized to [[pathToRegex.Return]] format (but without [[pathToRegex.KeyToIndex]]).
* So params in [[Context]] will be an object `number` indexed (start at `1` index)
* - or directly a [[pathToRegex.Return]]
*
* You are encouraged to use string [[Route]].
*
* `'/:category/:page/'` will provide you a params object with `categories` and `page` key in [[Context]]
*/
export type Route = string | RegExp | pathToRegex.Return;
/**
* All http methods supported by Node.js
*/
export type Method =
'GET' | 'POST' | 'HEAD' | 'PUT' | 'PATCH' | 'DELETE' |
'ACL' | 'BIND' | 'CHECKOUT' | 'CONNECT' | 'COPY' |
'LINK' | 'LOCK' | 'M-SEARCH' | 'MERGE' | 'MKACTIVITY' |
'MKCALENDAR' | 'MKCOL' | 'MOVE' | 'NOTIFY' | 'OPTIONS' |
'PROPFIND' | 'PROPPATCH' | 'PURGE' | 'REBIND' | 'REPORT' |
'SEARCH' | 'SOURCE' | 'SUBSCRIBE' | 'TRACE' | 'UNBIND' |
'UNLINK' | 'UNLOCK' | 'UNSUBSCRIBE';
export type Methods = Method | Method[];
export {cookies as parseCookie};
export {session as sessionInMemory};
}
/**
* ```js
* import App from 'u-http-server';
* ```
*
* This class let you create http, https, http2 builtin node server
* with simple api for middleware and routing.
*
* The api of this class is close to express or koa for easy adoption
* but all your routes or middlewares are handling in async await manner.
*
* instances of App have two separate stack, one for middlewares, the other for routes.
* - `use()` place in middlewares stack
* - `route()` and shortcut (`get()`, `post()`, etc.) place in routes stack
*
* They both have same syntax and called in the same way
*
* # Lyfecycle of a request
*
* When a server recieve a request,
* midlewares stack and routes stack are merged (middlewares first, next routes) in order they were declared
*
* Iterate on this merge.
* If methods and route match:
* - params are populated for route (/:categorie/:item => /cheese/camembert => {categorie: 'cheese', item: 'camenbert'})
* - middleware will be called in async way : `lastResult = await middleware(ctx, lastResult);`
* - When it terminate:
* - if `response.finished` break loop
* - else continue with next middleware in stack until no more middleware to handle.
*
* Next to last middleware, if not `response.finished`:
* `response.end(typeof lastResult === 'object' ? JSON.stringify(lastResult) : lastResult.toString());`
* It's for avoiding server never respond to client (and keep open ressources for nothing).
* And in your route, if you wan't return some data, you can. instead of calling yourself `response.end(data)` or `response.end(JSON.stringify(data))`
*
* /!\ For avoiding race exceptions, be sure when your middleware end,
* it has not open some asynchronous things not awaited.
* If you need to use some async api working with callback, wrap it in a Promise, resolve (or reject) it in callback
* and await or return this Promise.
*
* @example
*
* Some examples below
*
* ## Basic
* ```js
* import App, {parseCookie, sessionInMemory} from 'u-http-server';
*
* const app = new App();
*
* app
* .use(ctx => console.log(ctx.request.url))
* .use(parseCookie)
* .use(sessionInMemory)
* .get('/:category/:page', ctx => ctx.response.end(JSON.stringify(ctx.params)))
* .get('/:test', ctx => ctx.response.end(JSON.stringify(ctx.params)))
* .route(ctx => ctx.response.end('Hello World !'))
*
* app.init({protocol: 'http2', selfSigned: true})
* .then(app => app.applyOnClientError())
* .then(app => app.listen(3000))
* .then(url => console.log('server listening on', url));
* ```
*
* ## `lastReturn` mechanism
* ```js
* import fetch from 'node-fetch';
* import RSS from 'rss';
* import format from 'date-fns/format/index.js';
*
* const hytale_list = 'https://hytale.com/api/blog/post/published';
* const hytale_article = 'https://hytale.com/api/blog/post/slug/';
*
* const hytale_feed = feed_url => ({
* 'title': 'Hytale',
* 'description': 'News from Hytale',
* 'feed_url': feed_url,
* 'site_url': 'https://hytale.com/news',
* 'image_url': 'https://hytale.com/static/images/logo.png',
* });
*
* const getArticleUrl = item => `https://hytale.com/news/${format(item.createdAt, 'yyyy/MM')}/${item.slug}`;
*
* // fetch articles list from hytale api
* app.get('/rss/hytale', async ctx => {
* const articles_resume = await fetch(hytale_list).then(r => r.json());
*
* return Promise.all(
* articles_resume.map(a => fetch(hytale_article + a.slug).then(r => r.json()))
* );
* });
*
* // transform in to a rss feed
* app.get('/rss/hytale', (ctx, articles) => articles.reduce((feed, item) => feed.item({
* title: item.title,
* description: item.body,
* url: getArticleUrl(item),
* guid: `${item.slug}-${item._id}`,
* categories: item.tags,
* author: item.author,
* date: item.publishedAt,
* enclosure: {
* url: `https://hytale.com/m/variants/blog_cover_${item.coverImage.s3Key}`,
* type: item.coverImage.mimeType,
* }
* }), new RSS(hytale_feed(`${app.address}${ctx.request.url.toString()}`))).xml({indent: true}));
*
* // set content-type and end response with generated rss feed
* app.get('/rss/:flux', (ctx, rss) => {
* ctx.response.setHeader('Content-Type', 'application/rss+xml');
* ctx.response.end(rss);
* });
* ```
*/
declare class App {
private _middlewares: App.MiddlewareItem[];
private _routes: App.MiddlewareItem[];
private _server?: http.Server;
private _isSecure?: boolean;
/**
* populate next to call `await app.listen()` with server url
*
* @readonly
*/
public readonly address?: string;
/**
* Init server asynchronously
* can auto generate self-signed ssl if https or http2
*
* By default,
* ```js
* options = {protocol: 'http', selfSigned: false, http2Secure: true}
* ```
*
* If you wan't auto generate self-signed ssl:
* ```js
* init({protocol: 'https', selfSigned: true})
* // or
* init({protocol: 'http2', selfSigned: true})
* ```
*
* @param options
*/
public init(options: App.InitOptions): Promise<this>;
/**
* @param port - if no port provided, os take one available randomly. Think print resolved string url somewhere
* @param host - if no provided, 0.0.0.0
* @param backlog
*
* @return a string url of server
*/
public listen(port?: number, host?: string, backlog?: number): Promise<string>;
public listen(options: net.ListenOptions): Promise<string>;
/**
* if no callback provided it will use
*
* ```js
* (err, socket) => socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
* ```
*/
public applyOnClientError(callback?: (err: App.ClientError, socket: net.Socket) => void): this;
private _use(middleware: App.Middleware): App.ReturnPUse;
private _use(route: App.Route, middleware: App.Middleware): App.ReturnPUse;
private _use(methods: App.Methods, route: App.Route, middleware: App.Middleware): App.ReturnPUse;
/**
* Transform into a MiddlewareItem and put it in _middlewares stack
*
* @example
* ```js
* app.use(middleware); // equiv to app.use(http.METHODS, /^\/.*$/, middleware);
* app.use(route, middleware); // equiv to app.use(methods, route, middleware);
* app.use(methods, route, middleware);
* ```
*/
public use(middleware: App.Middleware): this;
public use(route: App.Route, middleware: App.Middleware): this;
public use(methods: App.Methods, route: App.Route, middleware: App.Middleware): this;
/**
* Transform into a MiddlewareItem and put it in _routes stack
*
* @example
* ```js
* app.route(middleware); // equiv to app.use(http.METHODS, /^\/.*$/, middleware);
* app.route(route, middleware); // equiv to app.use(http.METHODS, route, middleware);
* app.route(methods, route, middleware);
* ```
*/
public route(middleware: App.Middleware): this;
public route(route: App.Route, middleware: App.Middleware): this;
public route(methods: App.Methods, route: App.Route, middleware: App.Middleware): this;
/**
* @example
* ```js
* app.get(middleware); // equiv to app.get(/^\/.*$/, middleware);
* app.get(route, middleware); // equiv to app.route(['GET'], route, middleware)
* ```
*/
public get(middleware: App.Middleware): this;
public get(route: App.Route, middleware: App.Middleware): this;
/**
* @example
* ```js
* app.post(middleware); // equiv to app.post(/^\/.*$/, middleware);
* app.post(route, middleware); // equiv to app.route(['POST'], route, middleware)
* ```
*/
public post(middleware: App.Middleware): this;
public post(route: App.Route, middleware: App.Middleware): this;
/**
* @example
* ```js
* app.put(middleware); // equiv to app.put(/^\/.*$/, middleware);
* app.put(route, middleware); // equiv to app.route(['PUT'], route, middleware)
* ```
*/
public put(middleware: App.Middleware): this;
public put(route: App.Route, middleware: App.Middleware): this;
/**
* @example
* ```js
* app.patch(middleware); // equiv to app.patch(/^\/.*$/, middleware);
* app.patch(route, middleware); // equiv to app.route(['PATCH'], route, middleware)
* ```
*/
public patch(middleware: App.Middleware): this;
public patch(route: App.Route, middleware: App.Middleware): this;
/**
* @example
* ```js
* app.delete(middleware); // equiv to app.delete(/^\/.*$/, middleware);
* app.delete(route, middleware); // equiv to app.route(['DELETE'], route, middleware)
* ```
*/
public delete(middleware: App.Middleware): this;
public delete(route: App.Route, middleware: App.Middleware): this;
}
export = App;