@tylix/core 2.1.1 → 2.2.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.
- package/package.json +7 -7
- package/src/http/HttpError.d.ts +31 -0
- package/src/http/HttpError.js +86 -0
- package/src/http/Server.d.ts +15 -0
- package/src/http/Server.js +59 -8
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.1",
|
|
4
4
|
"description": "The Tylix server core: HTTP server and router, Laravel-style log channels, metrics and health checks, a shared store (memory, database, Redis), cache, rate limiting, a queue with retries and backoff, scheduler, channels and plugins.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Mbiyrukzz",
|
|
@@ -22,14 +22,14 @@
|
|
|
22
22
|
"backoff",
|
|
23
23
|
"scheduler"
|
|
24
24
|
],
|
|
25
|
-
"homepage": "https://github.com/
|
|
25
|
+
"homepage": "https://github.com/tylixjs/tylix/tree/main/packages/core#readme",
|
|
26
26
|
"repository": {
|
|
27
27
|
"type": "git",
|
|
28
|
-
"url": "git+https://github.com/
|
|
28
|
+
"url": "git+https://github.com/tylixjs/tylix.git",
|
|
29
29
|
"directory": "packages/core"
|
|
30
30
|
},
|
|
31
31
|
"bugs": {
|
|
32
|
-
"url": "https://github.com/
|
|
32
|
+
"url": "https://github.com/tylixjs/tylix/issues"
|
|
33
33
|
},
|
|
34
34
|
"engines": {
|
|
35
35
|
"node": ">=22.13"
|
|
@@ -50,9 +50,9 @@
|
|
|
50
50
|
"test": "node --test 'src/**/*.test.js'"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@tylix/auth": "^2.
|
|
54
|
-
"@tylix/orm": "^2.
|
|
55
|
-
"@tylix/shared": "^2.
|
|
53
|
+
"@tylix/auth": "^2.2.1",
|
|
54
|
+
"@tylix/orm": "^2.2.1",
|
|
55
|
+
"@tylix/shared": "^2.2.1",
|
|
56
56
|
"ws": "^8.18.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare const STATUS_TEXT: Record<number, string>
|
|
2
|
+
export declare const STATUS_MESSAGE: Record<number, string>
|
|
3
|
+
|
|
4
|
+
export interface HttpErrorOptions {
|
|
5
|
+
/** Show `message` to the visitor. Default: true for 4xx, false for 5xx. */
|
|
6
|
+
expose?: boolean
|
|
7
|
+
/** Extra response headers, e.g. { 'Retry-After': '60' }. */
|
|
8
|
+
headers?: Record<string, string>
|
|
9
|
+
cause?: unknown
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** An error with an HTTP status. The server answers with that status. */
|
|
13
|
+
export declare class HttpError extends Error {
|
|
14
|
+
constructor(status?: number, message?: string, options?: HttpErrorOptions)
|
|
15
|
+
readonly name: 'HttpError'
|
|
16
|
+
readonly status: number
|
|
17
|
+
readonly statusCode: number
|
|
18
|
+
readonly expose: boolean
|
|
19
|
+
readonly headers: Record<string, string>
|
|
20
|
+
readonly hasCustomMessage: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export declare function isHttpError(err: unknown): err is HttpError
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Stops the request with `status`: JSON for API calls, the app's
|
|
27
|
+
* app/pages/errors/<status>.tyx page (or the built-in one) for browsers.
|
|
28
|
+
*/
|
|
29
|
+
export declare function abort(status: number, message?: string, options?: HttpErrorOptions): never
|
|
30
|
+
|
|
31
|
+
export declare function describeStatus(status: number, message?: string): { title: string; message: string }
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// An error that already knows its HTTP status. Throw it (or call abort())
|
|
2
|
+
// anywhere a request runs: the server answers with that status instead of
|
|
3
|
+
// a 500, as JSON for API calls and as the app's error page
|
|
4
|
+
// (app/pages/errors/<status>.tyx) for browser navigations.
|
|
5
|
+
//
|
|
6
|
+
// import { abort } from '@tylix/core'
|
|
7
|
+
// if (!post) abort(404)
|
|
8
|
+
// if (post.ownerId !== req.user.userId) abort(403, "This post isn't yours.")
|
|
9
|
+
//
|
|
10
|
+
// 4xx errors are the client's doing and are not logged as failures. Their
|
|
11
|
+
// message is shown to the visitor, so keep secrets out of it. A 5xx
|
|
12
|
+
// message is only shown when `expose: true` is passed.
|
|
13
|
+
|
|
14
|
+
export const STATUS_TEXT = {
|
|
15
|
+
400: 'Bad request',
|
|
16
|
+
401: 'Sign in required',
|
|
17
|
+
402: 'Payment required',
|
|
18
|
+
403: 'Access denied',
|
|
19
|
+
404: 'Page not found',
|
|
20
|
+
405: 'Method not allowed',
|
|
21
|
+
408: 'Request timed out',
|
|
22
|
+
409: 'Conflict',
|
|
23
|
+
410: 'Gone',
|
|
24
|
+
413: 'Upload too large',
|
|
25
|
+
419: 'Page expired',
|
|
26
|
+
422: 'Unprocessable request',
|
|
27
|
+
429: 'Too many requests',
|
|
28
|
+
500: 'Something went wrong',
|
|
29
|
+
501: 'Not implemented',
|
|
30
|
+
502: 'Bad gateway',
|
|
31
|
+
503: 'Service unavailable',
|
|
32
|
+
504: 'Gateway timeout',
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const STATUS_MESSAGE = {
|
|
36
|
+
400: "The request couldn't be understood. Check the link and try again.",
|
|
37
|
+
401: 'Sign in to see this page.',
|
|
38
|
+
402: 'This needs an active plan.',
|
|
39
|
+
403: "You don't have permission to see this page.",
|
|
40
|
+
404: "The page you're looking for doesn't exist or has been moved.",
|
|
41
|
+
405: "This address doesn't accept that kind of request.",
|
|
42
|
+
408: 'The request took too long. Please try again.',
|
|
43
|
+
409: 'Something changed while you were working. Reload and try again.',
|
|
44
|
+
410: 'This page has been removed.',
|
|
45
|
+
413: 'What you sent is too large.',
|
|
46
|
+
419: 'This page expired. Reload it and try again.',
|
|
47
|
+
422: "Some of what you sent isn't valid.",
|
|
48
|
+
429: "You're going a little fast. Wait a moment and try again.",
|
|
49
|
+
500: 'The server hit an unexpected error. Please try again in a moment.',
|
|
50
|
+
501: "This isn't available yet.",
|
|
51
|
+
502: 'A service this page depends on did not answer properly.',
|
|
52
|
+
503: "We're down for maintenance or overloaded. Please try again shortly.",
|
|
53
|
+
504: 'A service this page depends on took too long to answer.',
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class HttpError extends Error {
|
|
57
|
+
constructor(status = 500, message, { expose, headers, cause } = {}) {
|
|
58
|
+
const code = Number.isInteger(status) && status >= 400 && status <= 599 ? status : 500
|
|
59
|
+
super(message ?? STATUS_TEXT[code] ?? 'Error', cause ? { cause } : undefined)
|
|
60
|
+
this.name = 'HttpError'
|
|
61
|
+
this.status = code
|
|
62
|
+
this.statusCode = code
|
|
63
|
+
// Whether `message` may be shown to the visitor.
|
|
64
|
+
this.expose = expose ?? code < 500
|
|
65
|
+
this.headers = headers ?? {}
|
|
66
|
+
this.hasCustomMessage = message !== undefined
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function isHttpError(err) {
|
|
71
|
+
return err instanceof HttpError || err?.name === 'HttpError'
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Stops the request with `status`. Never returns.
|
|
75
|
+
export function abort(status, message, options) {
|
|
76
|
+
throw new HttpError(status, message, options)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The title and message for an error page, for any status.
|
|
80
|
+
export function describeStatus(status, message) {
|
|
81
|
+
const family = status >= 500 ? 500 : 400
|
|
82
|
+
return {
|
|
83
|
+
title: STATUS_TEXT[status] ?? STATUS_TEXT[family],
|
|
84
|
+
message: message ?? STATUS_MESSAGE[status] ?? STATUS_MESSAGE[family],
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/http/Server.d.ts
CHANGED
|
@@ -6,6 +6,15 @@ export type NotFoundHandler = (
|
|
|
6
6
|
res: any,
|
|
7
7
|
) => boolean | void | Promise<boolean | void>
|
|
8
8
|
|
|
9
|
+
export interface ErrorPageInfo {
|
|
10
|
+
status: number
|
|
11
|
+
code: string
|
|
12
|
+
title: string
|
|
13
|
+
message: string
|
|
14
|
+
requestId: string | null
|
|
15
|
+
path: string
|
|
16
|
+
}
|
|
17
|
+
|
|
9
18
|
export interface ServerOptions {
|
|
10
19
|
/**
|
|
11
20
|
* Called when no route matches, before the default 404 JSON response.
|
|
@@ -31,6 +40,12 @@ export interface ServerOptions {
|
|
|
31
40
|
metrics?: boolean | import('../observability/index.js').MetricsRegistry
|
|
32
41
|
/** Compress JSON responses of at least minBytes (default 1024) with Brotli or gzip; false turns it off. */
|
|
33
42
|
compression?: false | { minBytes?: number }
|
|
43
|
+
/**
|
|
44
|
+
* Renders the app's own page for an error status (tylix dev/start pass
|
|
45
|
+
* one that uses app/pages/errors/<status>.tyx). Return the HTML, or
|
|
46
|
+
* null for the built-in status page.
|
|
47
|
+
*/
|
|
48
|
+
errorPage?: (req: unknown, status: number, info: ErrorPageInfo) => Promise<string | null> | string | null
|
|
34
49
|
|
|
35
50
|
/** Other origins allowed to send browser writes. Defaults to TRUSTED_ORIGINS. */
|
|
36
51
|
trustedOrigins?: string[]
|
package/src/http/Server.js
CHANGED
|
@@ -11,6 +11,7 @@ import { parseCookies } from './parseCookies.js'
|
|
|
11
11
|
import { buildDebugPayload } from './debug/buildDebugPayload.js'
|
|
12
12
|
import { renderDebugPage } from './debug/renderDebugPage.js'
|
|
13
13
|
import { renderStatusPage } from './statusPage.js'
|
|
14
|
+
import { describeStatus, isHttpError } from './HttpError.js'
|
|
14
15
|
|
|
15
16
|
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
16
17
|
const DEFAULT_MAX_BODY_BYTES = 1024 * 1024 // 1 MB
|
|
@@ -171,9 +172,14 @@ export class Server {
|
|
|
171
172
|
slowRequestMs,
|
|
172
173
|
metrics,
|
|
173
174
|
compression,
|
|
175
|
+
errorPage,
|
|
174
176
|
} = {},
|
|
175
177
|
) {
|
|
176
178
|
this.router = router
|
|
179
|
+
// Renders the app's own page for an error status (app/pages/errors/
|
|
180
|
+
// <status>.tyx). Called as errorPage(req, status, info) and returns
|
|
181
|
+
// the HTML, or null to use the built-in status page.
|
|
182
|
+
this.errorPage = errorPage ?? null
|
|
177
183
|
// Optional fallback called when no route matches, before the
|
|
178
184
|
// default 404 JSON response -- e.g. tylix dev uses this to serve
|
|
179
185
|
// static files from public/. Return true if it handled the
|
|
@@ -259,7 +265,7 @@ export class Server {
|
|
|
259
265
|
try {
|
|
260
266
|
await this.handle(req, res)
|
|
261
267
|
} catch (err) {
|
|
262
|
-
this.fail(req, res, err)
|
|
268
|
+
await this.fail(req, res, err)
|
|
263
269
|
}
|
|
264
270
|
})
|
|
265
271
|
}
|
|
@@ -355,7 +361,7 @@ export class Server {
|
|
|
355
361
|
if (handled) return
|
|
356
362
|
}
|
|
357
363
|
if (wantsHtml(req)) {
|
|
358
|
-
this.sendStatusPage(res, 404, {
|
|
364
|
+
await this.sendStatusPage(req, res, 404, {
|
|
359
365
|
tone: 'notfound',
|
|
360
366
|
code: '404',
|
|
361
367
|
title: 'Page not found',
|
|
@@ -435,20 +441,46 @@ export class Server {
|
|
|
435
441
|
})
|
|
436
442
|
}
|
|
437
443
|
|
|
438
|
-
fail(req, res, err) {
|
|
444
|
+
async fail(req, res, err) {
|
|
439
445
|
// A malformed %-escape in the URL is the client's fault, not a crash.
|
|
440
446
|
const badRequest = err instanceof URIError
|
|
447
|
+
// abort(403) and friends: a chosen status, not a crash. Only 5xx ones
|
|
448
|
+
// are logged.
|
|
449
|
+
const httpError = isHttpError(err) ? err : null
|
|
441
450
|
|
|
442
|
-
if (!badRequest) this.logFailure(req, err)
|
|
451
|
+
if (!badRequest && (!httpError || httpError.status >= 500)) this.logFailure(req, err)
|
|
443
452
|
|
|
444
453
|
if (res.headersSent) {
|
|
445
454
|
if (!res.writableEnded) res.end()
|
|
446
455
|
return
|
|
447
456
|
}
|
|
448
457
|
|
|
458
|
+
// Rendered even with APP_DEBUG on, like any deliberate response: the
|
|
459
|
+
// debug page is for crashes, and abort(503) during maintenance must
|
|
460
|
+
// look the same on every machine.
|
|
461
|
+
if (httpError) {
|
|
462
|
+
const { status } = httpError
|
|
463
|
+
for (const [name, value] of Object.entries(httpError.headers ?? {})) res.setHeader(name, value)
|
|
464
|
+
const shown = httpError.expose && httpError.hasCustomMessage ? httpError.message : undefined
|
|
465
|
+
if (wantsHtml(req)) {
|
|
466
|
+
const { title, message } = describeStatus(status, shown)
|
|
467
|
+
await this.sendStatusPage(req, res, status, {
|
|
468
|
+
tone: status === 404 ? 'notfound' : 'error',
|
|
469
|
+
code: String(status),
|
|
470
|
+
title,
|
|
471
|
+
message,
|
|
472
|
+
requestId: status >= 500 ? req.id : null,
|
|
473
|
+
actions: [{ label: 'Go home', href: '/' }],
|
|
474
|
+
})
|
|
475
|
+
return
|
|
476
|
+
}
|
|
477
|
+
res.status(status).json({ error: shown ?? describeStatus(status).title })
|
|
478
|
+
return
|
|
479
|
+
}
|
|
480
|
+
|
|
449
481
|
if (badRequest) {
|
|
450
482
|
if (wantsHtml(req)) {
|
|
451
|
-
this.sendStatusPage(res, 400, {
|
|
483
|
+
await this.sendStatusPage(req, res, 400, {
|
|
452
484
|
code: '400',
|
|
453
485
|
title: 'Bad request',
|
|
454
486
|
message: "The address of this page isn't valid. Check the link and try again.",
|
|
@@ -472,7 +504,7 @@ export class Server {
|
|
|
472
504
|
// A browser navigation gets a page, not JSON. The details stay in the
|
|
473
505
|
// log; the page shows the request id to match it up.
|
|
474
506
|
if (wantsHtml(req)) {
|
|
475
|
-
this.sendStatusPage(res, 500, {
|
|
507
|
+
await this.sendStatusPage(req, res, 500, {
|
|
476
508
|
code: '500',
|
|
477
509
|
title: 'Something went wrong',
|
|
478
510
|
message: 'The server hit an unexpected error. Please try again in a moment.',
|
|
@@ -490,11 +522,30 @@ export class Server {
|
|
|
490
522
|
})
|
|
491
523
|
}
|
|
492
524
|
|
|
493
|
-
|
|
525
|
+
// The app's errors/<status>.tyx page when it has one, else the built-in
|
|
526
|
+
// page. A broken error page must never hide the original error, so any
|
|
527
|
+
// failure here falls back to the built-in one.
|
|
528
|
+
async sendStatusPage(req, res, status, page) {
|
|
529
|
+
let html = null
|
|
530
|
+
if (this.errorPage) {
|
|
531
|
+
try {
|
|
532
|
+
html = await this.errorPage(req, status, {
|
|
533
|
+
status,
|
|
534
|
+
code: page.code ?? String(status),
|
|
535
|
+
title: page.title,
|
|
536
|
+
message: page.message,
|
|
537
|
+
requestId: page.requestId ?? null,
|
|
538
|
+
path: pathOf(req.url),
|
|
539
|
+
})
|
|
540
|
+
} catch (err) {
|
|
541
|
+
this.logger.error('Error page failed to render', { status, requestId: req.id, error: err })
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (res.headersSent) return
|
|
494
545
|
res.statusCode = status
|
|
495
546
|
res.setHeader('Content-Type', 'text/html; charset=utf-8')
|
|
496
547
|
res.setHeader('Cache-Control', 'no-store')
|
|
497
|
-
res.end(renderStatusPage(page))
|
|
548
|
+
res.end(html ?? renderStatusPage(page))
|
|
498
549
|
}
|
|
499
550
|
|
|
500
551
|
// Starts listening on `port`. If that port is taken and autoPort is on,
|
package/src/index.d.ts
CHANGED
package/src/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export * from './router/Router.js'
|
|
2
2
|
export * from './http/Server.js'
|
|
3
3
|
export * from './http/statusPage.js'
|
|
4
|
+
export * from './http/HttpError.js'
|
|
4
5
|
export { buildDebugPayload } from './http/debug/buildDebugPayload.js'
|
|
5
6
|
export { renderDebugPage } from './http/debug/renderDebugPage.js'
|
|
6
7
|
export * from './http/enhanceResponse.js'
|