@miqro/core 4.0.1 → 5.0.3
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/build/app.d.ts +15 -11
- package/build/app.js +22 -20
- package/build/app.js.map +1 -1
- package/build/common.d.ts +106 -0
- package/build/common.js +477 -0
- package/build/common.js.map +1 -0
- package/build/lib.d.ts +7 -38
- package/build/lib.js +6 -33
- package/build/lib.js.map +1 -1
- package/build/middleware/body-parser.d.ts +78 -0
- package/build/middleware/body-parser.js +548 -0
- package/build/middleware/body-parser.js.map +1 -0
- package/build/middleware/router.d.ts +114 -0
- package/build/middleware/router.js +704 -0
- package/build/middleware/router.js.map +1 -0
- package/build/middleware/session.d.ts +27 -3
- package/build/middleware/session.js +238 -18
- package/build/middleware/session.js.map +1 -1
- package/build/types.d.ts +309 -0
- package/build/types.js +455 -0
- package/build/types.js.map +1 -0
- package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
- package/build/websocket.js +316 -0
- package/build/websocket.js.map +1 -0
- package/package.json +7 -7
- package/src/app.ts +36 -32
- package/src/common.ts +528 -0
- package/src/lib.ts +63 -101
- package/src/middleware/body-parser.ts +593 -0
- package/src/middleware/router.ts +840 -0
- package/src/middleware/session.ts +249 -19
- package/src/types.ts +785 -0
- package/src/websocket.ts +356 -0
- package/build/api-router.d.ts +0 -34
- package/build/api-router.js +0 -48
- package/build/api-router.js.map +0 -1
- package/build/app-utils.d.ts +0 -13
- package/build/app-utils.js +0 -78
- package/build/app-utils.js.map +0 -1
- package/build/common/api-router-types.d.ts +0 -28
- package/build/common/api-router-types.js +0 -24
- package/build/common/api-router-types.js.map +0 -1
- package/build/common/api-router-utils.d.ts +0 -3
- package/build/common/api-router-utils.js +0 -118
- package/build/common/api-router-utils.js.map +0 -1
- package/build/common/config/config.d.ts +0 -15
- package/build/common/config/config.js +0 -38
- package/build/common/config/config.js.map +0 -1
- package/build/common/config/featuretoggle.d.ts +0 -1
- package/build/common/config/featuretoggle.js +0 -6
- package/build/common/config/featuretoggle.js.map +0 -1
- package/build/common/config/loader.d.ts +0 -13
- package/build/common/config/loader.js +0 -64
- package/build/common/config/loader.js.map +0 -1
- package/build/common/context.d.ts +0 -57
- package/build/common/context.js +0 -137
- package/build/common/context.js.map +0 -1
- package/build/common/error/badrequesterror.d.ts +0 -3
- package/build/common/error/badrequesterror.js +0 -7
- package/build/common/error/badrequesterror.js.map +0 -1
- package/build/common/error/configfilenotfound.d.ts +0 -3
- package/build/common/error/configfilenotfound.js +0 -7
- package/build/common/error/configfilenotfound.js.map +0 -1
- package/build/common/error/forbiddenerror.d.ts +0 -3
- package/build/common/error/forbiddenerror.js +0 -7
- package/build/common/error/forbiddenerror.js.map +0 -1
- package/build/common/error/notfound.d.ts +0 -3
- package/build/common/error/notfound.js +0 -7
- package/build/common/error/notfound.js.map +0 -1
- package/build/common/error/notimplemented.d.ts +0 -3
- package/build/common/error/notimplemented.js +0 -7
- package/build/common/error/notimplemented.js.map +0 -1
- package/build/common/error/unauthorizederror.d.ts +0 -3
- package/build/common/error/unauthorizederror.js +0 -7
- package/build/common/error/unauthorizederror.js.map +0 -1
- package/build/common/logger/constants.d.ts +0 -14
- package/build/common/logger/constants.js +0 -22
- package/build/common/logger/constants.js.map +0 -1
- package/build/common/logger/factory.d.ts +0 -16
- package/build/common/logger/factory.js +0 -47
- package/build/common/logger/factory.js.map +0 -1
- package/build/common/logger/interfaces.d.ts +0 -18
- package/build/common/logger/interfaces.js +0 -2
- package/build/common/logger/interfaces.js.map +0 -1
- package/build/common/logger/logger.d.ts +0 -35
- package/build/common/logger/logger.js +0 -95
- package/build/common/logger/logger.js.map +0 -1
- package/build/common/logger/transport/console.d.ts +0 -5
- package/build/common/logger/transport/console.js +0 -37
- package/build/common/logger/transport/console.js.map +0 -1
- package/build/common/logger/transport/file.d.ts +0 -2
- package/build/common/logger/transport/file.js +0 -25
- package/build/common/logger/transport/file.js.map +0 -1
- package/build/common/parser.d.ts +0 -7
- package/build/common/parser.js +0 -44
- package/build/common/parser.js.map +0 -1
- package/build/common/router-default-logger-factory.d.ts +0 -4
- package/build/common/router-default-logger-factory.js +0 -38
- package/build/common/router-default-logger-factory.js.map +0 -1
- package/build/common/router-handler.d.ts +0 -20
- package/build/common/router-handler.js +0 -154
- package/build/common/router-handler.js.map +0 -1
- package/build/common/router-types.d.ts +0 -63
- package/build/common/router-types.js +0 -86
- package/build/common/router-types.js.map +0 -1
- package/build/common/router-utils.d.ts +0 -3
- package/build/common/router-utils.js +0 -46
- package/build/common/router-utils.js.map +0 -1
- package/build/common/session/common.d.ts +0 -37
- package/build/common/session/common.js +0 -2
- package/build/common/session/common.js.map +0 -1
- package/build/common/session/service.d.ts +0 -26
- package/build/common/session/service.js +0 -154
- package/build/common/session/service.js.map +0 -1
- package/build/common/tokenize-match.d.ts +0 -19
- package/build/common/tokenize-match.js +0 -73
- package/build/common/tokenize-match.js.map +0 -1
- package/build/common/url-utils.d.ts +0 -6
- package/build/common/url-utils.js +0 -48
- package/build/common/url-utils.js.map +0 -1
- package/build/middleware/buffer.d.ts +0 -6
- package/build/middleware/buffer.js +0 -78
- package/build/middleware/buffer.js.map +0 -1
- package/build/middleware/cookie.d.ts +0 -4
- package/build/middleware/cookie.js +0 -15
- package/build/middleware/cookie.js.map +0 -1
- package/build/middleware/cors.d.ts +0 -8
- package/build/middleware/cors.js +0 -89
- package/build/middleware/cors.js.map +0 -1
- package/build/middleware/form.d.ts +0 -6
- package/build/middleware/form.js +0 -58
- package/build/middleware/form.js.map +0 -1
- package/build/middleware/group.d.ts +0 -3
- package/build/middleware/group.js +0 -77
- package/build/middleware/group.js.map +0 -1
- package/build/middleware/json.d.ts +0 -6
- package/build/middleware/json.js +0 -55
- package/build/middleware/json.js.map +0 -1
- package/build/middleware/logger.d.ts +0 -4
- package/build/middleware/logger.js +0 -16
- package/build/middleware/logger.js.map +0 -1
- package/build/middleware/parse.d.ts +0 -14
- package/build/middleware/parse.js +0 -88
- package/build/middleware/parse.js.map +0 -1
- package/build/middleware/result.d.ts +0 -9
- package/build/middleware/result.js +0 -62
- package/build/middleware/result.js.map +0 -1
- package/build/middleware/tag.d.ts +0 -4
- package/build/middleware/tag.js +0 -10
- package/build/middleware/tag.js.map +0 -1
- package/build/middleware/text.d.ts +0 -5
- package/build/middleware/text.js +0 -46
- package/build/middleware/text.js.map +0 -1
- package/build/proxy.d.ts +0 -19
- package/build/proxy.js +0 -74
- package/build/proxy.js.map +0 -1
- package/build/router.d.ts +0 -26
- package/build/router.js +0 -116
- package/build/router.js.map +0 -1
- package/build/static.d.ts +0 -14
- package/build/static.js +0 -211
- package/build/static.js.map +0 -1
- package/build/websocket/cluster.js +0 -114
- package/build/websocket/cluster.js.map +0 -1
- package/build/websocket/server.d.ts +0 -15
- package/build/websocket/server.js +0 -127
- package/build/websocket/server.js.map +0 -1
- package/build/websocket/types.d.ts +0 -39
- package/build/websocket/types.js +0 -2
- package/build/websocket/types.js.map +0 -1
- package/build/websocket/utils.d.ts +0 -8
- package/build/websocket/utils.js +0 -77
- package/build/websocket/utils.js.map +0 -1
- package/src/api-router.ts +0 -50
- package/src/app-utils.ts +0 -82
- package/src/common/api-router-types.ts +0 -52
- package/src/common/api-router-utils.ts +0 -126
- package/src/common/config/config.ts +0 -49
- package/src/common/config/featuretoggle.ts +0 -6
- package/src/common/config/loader.ts +0 -81
- package/src/common/context.ts +0 -192
- package/src/common/error/badrequesterror.ts +0 -6
- package/src/common/error/configfilenotfound.ts +0 -6
- package/src/common/error/forbiddenerror.ts +0 -6
- package/src/common/error/notfound.ts +0 -6
- package/src/common/error/notimplemented.ts +0 -6
- package/src/common/error/unauthorizederror.ts +0 -6
- package/src/common/logger/constants.ts +0 -28
- package/src/common/logger/factory.ts +0 -53
- package/src/common/logger/interfaces.ts +0 -19
- package/src/common/logger/logger.ts +0 -136
- package/src/common/logger/transport/console.ts +0 -36
- package/src/common/logger/transport/file.ts +0 -26
- package/src/common/parser.ts +0 -50
- package/src/common/router-default-logger-factory.ts +0 -44
- package/src/common/router-handler.ts +0 -186
- package/src/common/router-types.ts +0 -153
- package/src/common/router-utils.ts +0 -47
- package/src/common/session/common.ts +0 -40
- package/src/common/session/service.ts +0 -175
- package/src/common/tokenize-match.ts +0 -98
- package/src/common/url-utils.ts +0 -46
- package/src/middleware/buffer.ts +0 -82
- package/src/middleware/cookie.ts +0 -20
- package/src/middleware/cors.ts +0 -98
- package/src/middleware/form.ts +0 -61
- package/src/middleware/group.ts +0 -74
- package/src/middleware/json.ts +0 -57
- package/src/middleware/logger.ts +0 -18
- package/src/middleware/parse.ts +0 -105
- package/src/middleware/result.ts +0 -73
- package/src/middleware/tag.ts +0 -15
- package/src/middleware/text.ts +0 -47
- package/src/proxy.ts +0 -99
- package/src/router.ts +0 -140
- package/src/static.ts +0 -242
- package/src/websocket/cluster.ts +0 -128
- package/src/websocket/server.ts +0 -135
- package/src/websocket/types.ts +0 -41
- package/src/websocket/utils.ts +0 -95
package/src/static.ts
DELETED
|
@@ -1,242 +0,0 @@
|
|
|
1
|
-
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
|
|
2
|
-
import { extname, resolve } from "path";
|
|
3
|
-
import { Context } from "./common/context.js";
|
|
4
|
-
import { PathPartToken } from "./common/tokenize-match.js";
|
|
5
|
-
import { Router } from "./router.js";
|
|
6
|
-
import { RouterOptions } from "./common/router-types.js";
|
|
7
|
-
import { assertNotUndefined, DEFAULT_PARSER } from "./common/parser.js";
|
|
8
|
-
|
|
9
|
-
const outputFile = async (path: string, contentType: string, ctx: Context, allowGetJSON: boolean, status = 200) => {
|
|
10
|
-
const buffer = readFileSync(path);
|
|
11
|
-
return allowGetJSON && ctx.query.format && ctx.query.format === "json" ?
|
|
12
|
-
ctx.json({
|
|
13
|
-
buffer
|
|
14
|
-
}) :
|
|
15
|
-
ctx.end({
|
|
16
|
-
status,
|
|
17
|
-
headers: {
|
|
18
|
-
["Content-Type"]: contentType
|
|
19
|
-
},
|
|
20
|
-
body: buffer
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const generateList = async (path: string, ctx: Context, allowListJSON: boolean) => {
|
|
25
|
-
const files = readdirSync(path);
|
|
26
|
-
return allowListJSON && ctx.query.format && ctx.query.format === "json" ?
|
|
27
|
-
ctx.json({ files: files.map(f => `${ctx.path}${f}`) }) :
|
|
28
|
-
ctx.html(`<html><body><ul>${files.map(f => `<li><a href="${ctx.path}${f}">${f}</a></li>`).join("")}</ul></body></html>`);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface StaticRouterOptions extends RouterOptions {
|
|
32
|
-
directory: string;
|
|
33
|
-
list?: boolean;
|
|
34
|
-
allowListJSON?: boolean;
|
|
35
|
-
allowGetJSON?: boolean;
|
|
36
|
-
index?: string;
|
|
37
|
-
index404?: string;
|
|
38
|
-
index404Status?: number;
|
|
39
|
-
contentTypes?: any;
|
|
40
|
-
defaultContentType?: string;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function Static(options: StaticRouterOptions): Router {
|
|
44
|
-
return new StaticRouter(options);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
class StaticRouter extends Router {
|
|
48
|
-
|
|
49
|
-
private readonly staticOptions: {
|
|
50
|
-
directory: string;
|
|
51
|
-
list: boolean;
|
|
52
|
-
allowListJSON: boolean;
|
|
53
|
-
allowGetJSON: boolean;
|
|
54
|
-
index: string;
|
|
55
|
-
index404: string;
|
|
56
|
-
index404Status: number;
|
|
57
|
-
contentTypes: any;
|
|
58
|
-
defaultContentType: string;
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
constructor(options: StaticRouterOptions) {
|
|
62
|
-
super(options);
|
|
63
|
-
this.staticOptions = assertNotUndefined(DEFAULT_PARSER.parse(options, {
|
|
64
|
-
type: "object",
|
|
65
|
-
properties: {
|
|
66
|
-
loggerFactory: {
|
|
67
|
-
required: false,
|
|
68
|
-
type: "any"
|
|
69
|
-
},
|
|
70
|
-
directory: {
|
|
71
|
-
type: "string",
|
|
72
|
-
required: true
|
|
73
|
-
},
|
|
74
|
-
list: {
|
|
75
|
-
type: "boolean",
|
|
76
|
-
required: false,
|
|
77
|
-
defaultValue: false
|
|
78
|
-
},
|
|
79
|
-
allowListJSON: {
|
|
80
|
-
type: "boolean",
|
|
81
|
-
required: false,
|
|
82
|
-
defaultValue: false
|
|
83
|
-
},
|
|
84
|
-
allowGetJSON: {
|
|
85
|
-
type: "boolean",
|
|
86
|
-
required: false,
|
|
87
|
-
defaultValue: false
|
|
88
|
-
},
|
|
89
|
-
index: {
|
|
90
|
-
type: "string",
|
|
91
|
-
required: false,
|
|
92
|
-
defaultValue: "index.html"
|
|
93
|
-
},
|
|
94
|
-
index404: {
|
|
95
|
-
type: "string",
|
|
96
|
-
required: false
|
|
97
|
-
},
|
|
98
|
-
index404Status: {
|
|
99
|
-
type: "number",
|
|
100
|
-
required: false,
|
|
101
|
-
defaultValue: 404
|
|
102
|
-
},
|
|
103
|
-
contentTypes: {
|
|
104
|
-
type: "object",
|
|
105
|
-
required: false,
|
|
106
|
-
defaultValue: {
|
|
107
|
-
".aac": "audio/aac",
|
|
108
|
-
".abw": "application/x-abiword",
|
|
109
|
-
".arc": "application/x-freearc",
|
|
110
|
-
".avif": "image/avif",
|
|
111
|
-
".avi": "video/x-msvideo",
|
|
112
|
-
".azw": "application/vnd.amazon.ebook",
|
|
113
|
-
".bin": "application/octet-stream",
|
|
114
|
-
".bmp": "image/bmp",
|
|
115
|
-
".bz": "application/x-bzip",
|
|
116
|
-
".bz2": "application/x-bzip2",
|
|
117
|
-
".cda": "application/x-cdf",
|
|
118
|
-
".csh": "application/x-csh",
|
|
119
|
-
".css": "text/css",
|
|
120
|
-
".csv": "text/csv",
|
|
121
|
-
".doc": "application/msword",
|
|
122
|
-
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
123
|
-
".eot": "application/vnd.ms-fontobject",
|
|
124
|
-
".epub": "application/epub+zip",
|
|
125
|
-
".gz": "application/gzip",
|
|
126
|
-
".gif": "image/gif",
|
|
127
|
-
".htm": "text/html",
|
|
128
|
-
".html": "text/html",
|
|
129
|
-
".ico": "image/vnd.microsoft.icon",
|
|
130
|
-
".ics": "text/calendar",
|
|
131
|
-
".jar": "application/java-archive",
|
|
132
|
-
".jpeg": "image/jpeg",
|
|
133
|
-
".jpg": "image/jpeg",
|
|
134
|
-
".js": "text/javascript",
|
|
135
|
-
".json": "application/json",
|
|
136
|
-
".jsonld": "application/ld+json",
|
|
137
|
-
".mid": "audio/midi audio/x-midi",
|
|
138
|
-
".midi": "audio/midi audio/x-midi",
|
|
139
|
-
".mjs": "text/javascript",
|
|
140
|
-
".mp3": "audio/mpeg",
|
|
141
|
-
".mp4": "video/mp4",
|
|
142
|
-
".mpeg": "video/mpeg",
|
|
143
|
-
".mpkg": "application/vnd.apple.installer+xml",
|
|
144
|
-
".odp": "application/vnd.oasis.opendocument.presentation",
|
|
145
|
-
".ods": "application/vnd.oasis.opendocument.spreadsheet",
|
|
146
|
-
".odt": "application/vnd.oasis.opendocument.text",
|
|
147
|
-
".oga": "audio/ogg",
|
|
148
|
-
".ogv": "video/ogg",
|
|
149
|
-
".ogx": "application/ogg",
|
|
150
|
-
".opus": "audio/opus",
|
|
151
|
-
".otf": "font/otf",
|
|
152
|
-
".png": "image/png",
|
|
153
|
-
".pdf": "application/pdf",
|
|
154
|
-
".php": "application/x-httpd-php",
|
|
155
|
-
".ppt": "application/vnd.ms-powerpoint",
|
|
156
|
-
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
157
|
-
".rar": "application/vnd.rar",
|
|
158
|
-
".rtf": "application/rtf",
|
|
159
|
-
".sh": "application/x-sh",
|
|
160
|
-
".svg": "image/svg+xml",
|
|
161
|
-
".swf": "application/x-shockwave-flash",
|
|
162
|
-
".tar": "application/x-tar",
|
|
163
|
-
".tif": "image/tiff",
|
|
164
|
-
".tiff": "image/tiff",
|
|
165
|
-
".ts": "video/mp2t",
|
|
166
|
-
".ttf": "font/ttf",
|
|
167
|
-
".txt": "text/plain",
|
|
168
|
-
".vsd": "application/vnd.visio",
|
|
169
|
-
".wav": "audio/wav",
|
|
170
|
-
".weba": "audio/webm",
|
|
171
|
-
".webm": "video/webm",
|
|
172
|
-
".webp": "image/webp",
|
|
173
|
-
".woff": "font/woff",
|
|
174
|
-
".woff2": "font/woff2",
|
|
175
|
-
".xhtml": "application/xhtml+xml",
|
|
176
|
-
".xls": "application/vnd.ms-excel",
|
|
177
|
-
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
178
|
-
".xml": "application/xml",
|
|
179
|
-
".xul": "application/vnd.mozilla.xul+xml",
|
|
180
|
-
".zip": "application/zip",
|
|
181
|
-
".3gp": "video/3gpp; audio/3gpp",
|
|
182
|
-
".3g2": "video/3gpp2; audio/3gpp2",
|
|
183
|
-
".7z": "application/x-7z-compressed"
|
|
184
|
-
}
|
|
185
|
-
},
|
|
186
|
-
defaultContentType: {
|
|
187
|
-
type: "string",
|
|
188
|
-
required: false,
|
|
189
|
-
defaultValue: "application/octet-stream"
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
}, "options"), "bad options");
|
|
193
|
-
if (!statSync(this.staticOptions.directory).isDirectory()) {
|
|
194
|
-
throw new Error(`options.directory ${this.staticOptions.directory} not a directory`);
|
|
195
|
-
}
|
|
196
|
-
if (this.staticOptions.index404 && !existsSync(resolve(this.staticOptions.directory, this.staticOptions.index404))) {
|
|
197
|
-
throw new Error(`options.index404 ${this.staticOptions.index404} not a found`);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
202
|
-
const { directory, allowGetJSON, allowListJSON, list, index, contentTypes, defaultContentType } = this.staticOptions;
|
|
203
|
-
const level = prePathTokens.length;
|
|
204
|
-
if (ctx.method === "GET") {
|
|
205
|
-
const realPath = resolve(directory, ctx.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/"));
|
|
206
|
-
ctx.logger.debug("static get %s", realPath);
|
|
207
|
-
|
|
208
|
-
if (existsSync(realPath)) {
|
|
209
|
-
if (statSync(realPath).isDirectory()) {
|
|
210
|
-
// directory
|
|
211
|
-
const indexPath = resolve(realPath, index);
|
|
212
|
-
if (index && existsSync(indexPath) && statSync(indexPath).isFile()) {
|
|
213
|
-
// index file exists
|
|
214
|
-
const ext = extname(indexPath);
|
|
215
|
-
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
216
|
-
await outputFile(indexPath, contentType, ctx, allowGetJSON);
|
|
217
|
-
} else {
|
|
218
|
-
// index doesn't exists
|
|
219
|
-
if (list) {
|
|
220
|
-
// generate list
|
|
221
|
-
await generateList(realPath, ctx, allowListJSON);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
} else {
|
|
225
|
-
// direct file access
|
|
226
|
-
const ext = extname(realPath);
|
|
227
|
-
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
228
|
-
await outputFile(realPath, contentType, ctx, allowGetJSON);
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
if (this.staticOptions.index404) {
|
|
233
|
-
const realPath = resolve(this.staticOptions.directory, this.staticOptions.index404);
|
|
234
|
-
if (existsSync(realPath)) {
|
|
235
|
-
const ext = extname(realPath);
|
|
236
|
-
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
237
|
-
await outputFile(realPath, contentType, ctx, allowGetJSON, this.staticOptions.index404Status);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
return !ctx.res.headersSent ? super.run(ctx, pathTokens, prePathTokens) : false;
|
|
241
|
-
}
|
|
242
|
-
}
|
package/src/websocket/cluster.ts
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
import { Serializable } from "child_process";
|
|
2
|
-
import { WebSocketServer } from "./server.js";
|
|
3
|
-
import { WebSocketServerOptions } from "./types.js";
|
|
4
|
-
|
|
5
|
-
const ClusterWebSocketServerMessageType = "ClusterWebSocketServerMessage";
|
|
6
|
-
|
|
7
|
-
export interface ClusterWebSocketServerMessage {
|
|
8
|
-
type: typeof ClusterWebSocketServerMessageType;
|
|
9
|
-
action: "connection" | "disconnection" | "sendMessage";
|
|
10
|
-
clientUUID?: string;
|
|
11
|
-
fromUUID?: string;
|
|
12
|
-
payload?: Serializable;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export class ClusterWebSocketServer extends WebSocketServer {
|
|
16
|
-
public static instance: ClusterWebSocketServer;
|
|
17
|
-
public remoteClients: Set<string> = new Set();
|
|
18
|
-
public constructor(options: WebSocketServerOptions) {
|
|
19
|
-
super({
|
|
20
|
-
...options,
|
|
21
|
-
validate: (req) => {
|
|
22
|
-
if (
|
|
23
|
-
this.options.maxConnections !== undefined &&
|
|
24
|
-
this.clients.size + this.remoteClients.size >= this.options.maxConnections
|
|
25
|
-
) {
|
|
26
|
-
return false;
|
|
27
|
-
} else {
|
|
28
|
-
return options.validate ? options.validate(req) : true;
|
|
29
|
-
}
|
|
30
|
-
},
|
|
31
|
-
onConnection: (req) => {
|
|
32
|
-
if (process.send) {
|
|
33
|
-
process.send({
|
|
34
|
-
type: ClusterWebSocketServerMessageType,
|
|
35
|
-
action: "connection",
|
|
36
|
-
clientUUID: req.uuid
|
|
37
|
-
} as ClusterWebSocketServerMessage);
|
|
38
|
-
}
|
|
39
|
-
if (options.onConnection) {
|
|
40
|
-
options.onConnection(req);
|
|
41
|
-
}
|
|
42
|
-
},
|
|
43
|
-
onDisconnect: (req) => {
|
|
44
|
-
if (process.send) {
|
|
45
|
-
process.send({
|
|
46
|
-
type: ClusterWebSocketServerMessageType,
|
|
47
|
-
action: "disconnection",
|
|
48
|
-
clientUUID: req.uuid
|
|
49
|
-
} as ClusterWebSocketServerMessage);
|
|
50
|
-
}
|
|
51
|
-
if (options.onDisconnect) {
|
|
52
|
-
options.onDisconnect(req);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
});
|
|
56
|
-
if (ClusterWebSocketServer.instance) {
|
|
57
|
-
throw new Error("cannot create more than one instance");
|
|
58
|
-
}
|
|
59
|
-
ClusterWebSocketServer.instance = this;
|
|
60
|
-
if (process.send) {
|
|
61
|
-
process.on("message", (data) => {
|
|
62
|
-
const msg = (data as ClusterWebSocketServerMessage);
|
|
63
|
-
if (
|
|
64
|
-
msg &&
|
|
65
|
-
msg.type === ClusterWebSocketServerMessageType &&
|
|
66
|
-
msg.action) {
|
|
67
|
-
// receive message from cluster workers
|
|
68
|
-
switch (msg.action) {
|
|
69
|
-
case "connection":
|
|
70
|
-
if (!msg.clientUUID) {
|
|
71
|
-
throw new Error(`action [${msg.action}] without clientUUID`);
|
|
72
|
-
}
|
|
73
|
-
this.remoteClients.add(msg.clientUUID);
|
|
74
|
-
break;
|
|
75
|
-
case "disconnection":
|
|
76
|
-
if (!msg.clientUUID) {
|
|
77
|
-
throw new Error(`action [${msg.action}] without clientUUID`);
|
|
78
|
-
}
|
|
79
|
-
this.remoteClients.delete(msg.clientUUID);
|
|
80
|
-
break;
|
|
81
|
-
case "sendMessage": {
|
|
82
|
-
const data = String(msg.payload);
|
|
83
|
-
if (msg.clientUUID && this.isConnected(msg.clientUUID)) {
|
|
84
|
-
// write if local client
|
|
85
|
-
super.writeTo(msg.clientUUID, data);
|
|
86
|
-
} else {
|
|
87
|
-
super.broadcast(data, msg.fromUUID);
|
|
88
|
-
}
|
|
89
|
-
break;
|
|
90
|
-
}
|
|
91
|
-
default:
|
|
92
|
-
throw new Error(`action [${msg.action}] not supported`);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
public async broadcast(payload: string, fromUUID?: string): Promise<void> {
|
|
100
|
-
if (process.send) {
|
|
101
|
-
process.send({
|
|
102
|
-
type: ClusterWebSocketServerMessageType,
|
|
103
|
-
action: "sendMessage",
|
|
104
|
-
payload,
|
|
105
|
-
fromUUID
|
|
106
|
-
} as ClusterWebSocketServerMessage);
|
|
107
|
-
}
|
|
108
|
-
super.broadcast(payload, fromUUID);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
public async writeTo(clientUUID: string, payload: string): Promise<void> {
|
|
112
|
-
if (this.remoteClients.has(clientUUID)) {
|
|
113
|
-
// write to remote client via IPC
|
|
114
|
-
if (process.send) {
|
|
115
|
-
process.send({
|
|
116
|
-
type: ClusterWebSocketServerMessageType,
|
|
117
|
-
action: "sendMessage",
|
|
118
|
-
clientUUID,
|
|
119
|
-
payload
|
|
120
|
-
} as ClusterWebSocketServerMessage);
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
} else {
|
|
124
|
-
// write to local client
|
|
125
|
-
super.writeTo(clientUUID, payload);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
}
|
package/src/websocket/server.ts
DELETED
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "crypto";
|
|
2
|
-
import { IncomingMessage } from "http";
|
|
3
|
-
import { Duplex } from "stream";
|
|
4
|
-
import { Upgrader, WebSocketClient, WebSocketServerOptions } from "./types.js";
|
|
5
|
-
import { createFrame, createUpgradeHeaders, parseFrame } from "./utils.js";
|
|
6
|
-
|
|
7
|
-
export class WebSocketServer implements Upgrader {
|
|
8
|
-
public readonly clients: Map<string, WebSocketClient> = new Map();
|
|
9
|
-
|
|
10
|
-
constructor(public readonly options: WebSocketServerOptions) {
|
|
11
|
-
this.onUpgrade = this.onUpgrade.bind(this);
|
|
12
|
-
this.isConnected = this.isConnected.bind(this);
|
|
13
|
-
this.writeTo = this.writeTo.bind(this);
|
|
14
|
-
this.broadcast = this.broadcast.bind(this);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
public isConnected(clientUUID: string) {
|
|
18
|
-
return this.clients.get(clientUUID) !== undefined;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
public async broadcast(data: string, fromUUID?: string) {
|
|
22
|
-
const tR = [];
|
|
23
|
-
const clients = this.clients.values();
|
|
24
|
-
for (const client of clients) {
|
|
25
|
-
if (fromUUID === undefined || client.uuid !== fromUUID) {
|
|
26
|
-
tR.push(this.writeTo(client.uuid, data));
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
await Promise.all(tR);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
public async writeTo(clientUUID: string, data: string) {
|
|
33
|
-
const client = this.clients.get(clientUUID);
|
|
34
|
-
if (!client) {
|
|
35
|
-
throw new Error("client not found");
|
|
36
|
-
}
|
|
37
|
-
return new Promise<void>((resolve, reject) => {
|
|
38
|
-
try {
|
|
39
|
-
client.req.socket.write(createFrame(data), function SocketWriteCallback(err?: Error) {
|
|
40
|
-
if (err) {
|
|
41
|
-
reject(err);
|
|
42
|
-
} else {
|
|
43
|
-
resolve();
|
|
44
|
-
}
|
|
45
|
-
})
|
|
46
|
-
} catch (e) {
|
|
47
|
-
reject(e);
|
|
48
|
-
}
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
public async onUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer) {
|
|
53
|
-
const acceptKey = req.headers["sec-websocket-key"];
|
|
54
|
-
if (
|
|
55
|
-
!socket ||
|
|
56
|
-
(!req.headers.connection || req.headers.connection.indexOf("Upgrade") === -1) ||
|
|
57
|
-
req.headers.upgrade !== "websocket" ||
|
|
58
|
-
req.method !== "GET" ||
|
|
59
|
-
!acceptKey
|
|
60
|
-
) {
|
|
61
|
-
socket.end("HTTP/1.1 400 Bad Request");
|
|
62
|
-
socket.destroy();
|
|
63
|
-
return;
|
|
64
|
-
} else {
|
|
65
|
-
const validateRet = this.options.validate ? await this.options.validate(req) : true;
|
|
66
|
-
const uuid = typeof validateRet === "boolean" ?
|
|
67
|
-
(validateRet ? randomUUID() : null) :
|
|
68
|
-
(typeof validateRet === "object" ? validateRet.uuid :
|
|
69
|
-
validateRet ? randomUUID() : null
|
|
70
|
-
);
|
|
71
|
-
const extraHeaders = typeof validateRet === "object" ? validateRet.headers : undefined;
|
|
72
|
-
if (!uuid) {
|
|
73
|
-
socket.end("HTTP/1.1 403 Forbidden");
|
|
74
|
-
socket.destroy();
|
|
75
|
-
return;
|
|
76
|
-
} else {
|
|
77
|
-
if (this.options.maxConnections !== undefined && this.clients.size >= this.options.maxConnections) {
|
|
78
|
-
socket.end("HTTP/1.1 403 Forbidden");
|
|
79
|
-
socket.destroy();
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
const client: WebSocketClient = {
|
|
83
|
-
uuid,
|
|
84
|
-
head,
|
|
85
|
-
req,
|
|
86
|
-
socket
|
|
87
|
-
};
|
|
88
|
-
this.options.logger?.debug("upgrading connection");
|
|
89
|
-
|
|
90
|
-
socket.write(createUpgradeHeaders(acceptKey, extraHeaders));
|
|
91
|
-
|
|
92
|
-
socket.on("data", (data: Buffer) => {
|
|
93
|
-
const frame = parseFrame(data);
|
|
94
|
-
if (frame !== null) {
|
|
95
|
-
if (!this.options.onMessage) {
|
|
96
|
-
socket.end();
|
|
97
|
-
socket.destroy();
|
|
98
|
-
} else {
|
|
99
|
-
try {
|
|
100
|
-
this.options.onMessage(client, frame);
|
|
101
|
-
} catch (e) {
|
|
102
|
-
this.options.logger?.error(e);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
});
|
|
107
|
-
|
|
108
|
-
socket.on("end", () => {
|
|
109
|
-
this.options.logger?.debug("upgraded connection disconnected!");
|
|
110
|
-
this.clients.delete(uuid);
|
|
111
|
-
if (this.options.onDisconnect) {
|
|
112
|
-
try {
|
|
113
|
-
this.options.onDisconnect(client);
|
|
114
|
-
} catch (e) {
|
|
115
|
-
this.options.logger?.error(e);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
this.options.logger?.debug("connection upgraded");
|
|
121
|
-
this.clients.set(uuid, client);
|
|
122
|
-
if (this.options.onConnection) {
|
|
123
|
-
try {
|
|
124
|
-
this.options.onConnection(client);
|
|
125
|
-
} catch (e) {
|
|
126
|
-
this.options.logger?.error(e);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
|
package/src/websocket/types.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { IncomingMessage } from "http";
|
|
2
|
-
import { Duplex } from "stream";
|
|
3
|
-
|
|
4
|
-
export interface OnUpgrade {
|
|
5
|
-
(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> | void;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export interface Upgrader {
|
|
9
|
-
onUpgrade: OnUpgrade;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export interface ComplexValidateResult {
|
|
13
|
-
uuid?: string;
|
|
14
|
-
headers?: {
|
|
15
|
-
name: string;
|
|
16
|
-
value: string;
|
|
17
|
-
}[];
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export interface WebSocketServerOptions {
|
|
21
|
-
maxConnections?: number;
|
|
22
|
-
validate?: (req: IncomingMessage) => Promise<boolean | string | ComplexValidateResult> | boolean | string | ComplexValidateResult;
|
|
23
|
-
onConnection?: (req: WebSocketClient) => void;
|
|
24
|
-
onMessage?: (req: WebSocketClient, data: string | undefined | null) => void;
|
|
25
|
-
onDisconnect?: (req: WebSocketClient) => void;
|
|
26
|
-
logger?: {
|
|
27
|
-
log(message?: any, ...optionalParams: any[]): void;
|
|
28
|
-
info(message?: any, ...optionalParams: any[]): void;
|
|
29
|
-
trace(message?: any, ...optionalParams: any[]): void;
|
|
30
|
-
debug(message?: any, ...optionalParams: any[]): void;
|
|
31
|
-
warn(message?: any, ...optionalParams: any[]): void;
|
|
32
|
-
error(message?: any, ...optionalParams: any[]): void;
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface WebSocketClient {
|
|
37
|
-
uuid: string;
|
|
38
|
-
req: IncomingMessage;
|
|
39
|
-
socket: Duplex;
|
|
40
|
-
head: Buffer;
|
|
41
|
-
}
|
package/src/websocket/utils.ts
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { createHash } from "crypto";
|
|
2
|
-
|
|
3
|
-
const OPCODES = { text: 0x01, close: 0x08 };
|
|
4
|
-
const GUID: string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
5
|
-
//Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
|
|
6
|
-
export function createUpgradeHeaders(acceptKey: string, extraHeaders?: {
|
|
7
|
-
name: string;
|
|
8
|
-
value: string;
|
|
9
|
-
}[]) {
|
|
10
|
-
const acceptValue = createHash('sha1')
|
|
11
|
-
.update(acceptKey + GUID, 'binary')
|
|
12
|
-
.digest('base64');
|
|
13
|
-
let extra = extraHeaders && extraHeaders.length > 0 ? `\r\n${extraHeaders.map(h => `${h.name}: ${h.value}`).join("\r\n")}` : "";
|
|
14
|
-
return `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptValue}${extra}\r\n\r\n`;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function parseFrame(buffer: Buffer) {
|
|
18
|
-
const firstByte = buffer.readUInt8(0);
|
|
19
|
-
const opCode = firstByte & 0b00001111; // get last 4 bits of a byte
|
|
20
|
-
|
|
21
|
-
if (opCode === OPCODES.close) {
|
|
22
|
-
//this.emit('close');
|
|
23
|
-
return null;
|
|
24
|
-
} else if (opCode !== OPCODES.text) {
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const secondByte = buffer.readUInt8(1); // start with a payload length
|
|
29
|
-
|
|
30
|
-
let offset = 2;
|
|
31
|
-
let payloadLength = secondByte & 0b01111111; // get last 7 bits of a second byte
|
|
32
|
-
|
|
33
|
-
if (payloadLength === 126) {
|
|
34
|
-
offset += 2;
|
|
35
|
-
} else if (payloadLength === 127) {
|
|
36
|
-
offset += 8;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const isMasked = Boolean((secondByte >>> 7) & 0x1); // get first bit of a second byte
|
|
40
|
-
|
|
41
|
-
if (isMasked) {
|
|
42
|
-
const maskingKey = buffer.readUInt32BE(offset); // read 4-byte mask
|
|
43
|
-
offset += 4;
|
|
44
|
-
const payload = buffer.subarray(offset);
|
|
45
|
-
const result = unmask(payload, maskingKey);
|
|
46
|
-
return result.toString('utf-8');
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
return buffer.subarray(offset).toString('utf-8');
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function unmask(payload: Buffer, maskingKey: number) {
|
|
53
|
-
const result = Buffer.alloc(payload.byteLength);
|
|
54
|
-
|
|
55
|
-
for (let i = 0; i < payload.byteLength; ++i) {
|
|
56
|
-
const j = i % 4;
|
|
57
|
-
const maskingKeyByteShift = j === 3 ? 0 : (3 - j) << 3;
|
|
58
|
-
const maskingKeyByte = (maskingKeyByteShift === 0 ? maskingKey : maskingKey >>> maskingKeyByteShift) & 0b11111111;
|
|
59
|
-
const transformedByte = maskingKeyByte ^ payload.readUInt8(i);
|
|
60
|
-
result.writeUInt8(transformedByte, i);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return result;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export function createFrame(payload: string) {
|
|
67
|
-
|
|
68
|
-
const payloadByteLength = Buffer.byteLength(payload);
|
|
69
|
-
let payloadBytesOffset = 2;
|
|
70
|
-
let payloadLength = payloadByteLength;
|
|
71
|
-
|
|
72
|
-
if (payloadByteLength > 65535) { // length value cannot fit in 2 bytes
|
|
73
|
-
payloadBytesOffset += 8;
|
|
74
|
-
payloadLength = 127;
|
|
75
|
-
} else if (payloadByteLength > 125) {
|
|
76
|
-
payloadBytesOffset += 2;
|
|
77
|
-
payloadLength = 126;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const buffer = Buffer.alloc(payloadBytesOffset + payloadByteLength);
|
|
81
|
-
|
|
82
|
-
// first byte
|
|
83
|
-
buffer.writeUInt8(0b10000001, 0); // [FIN (1), RSV1 (0), RSV2 (0), RSV3 (0), Opode (0x01 - text frame)]
|
|
84
|
-
|
|
85
|
-
buffer[1] = payloadLength; // second byte - actual payload size (if <= 125 bytes) or 126, or 127
|
|
86
|
-
|
|
87
|
-
if (payloadLength === 126) { // write actual payload length as a 16-bit unsigned integer
|
|
88
|
-
buffer.writeUInt16BE(payloadByteLength, 2);
|
|
89
|
-
} else if (payloadByteLength === 127) { // write actual payload length as a 64-bit unsigned integer
|
|
90
|
-
buffer.writeBigUInt64BE(BigInt(payloadByteLength), 2);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
buffer.write(payload, payloadBytesOffset);
|
|
94
|
-
return buffer;
|
|
95
|
-
}
|