@miqro/core 1.5.9 → 1.5.10
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 +4 -4
- package/src/api-router.ts +51 -0
- package/src/app.ts +136 -0
- package/src/common/api-router-helpers.ts +32 -0
- package/src/common/api-router-utils.ts +206 -0
- package/src/common/config/config.ts +99 -0
- package/src/common/config/featuretoggle.ts +6 -0
- package/src/common/config/index.ts +3 -0
- package/src/common/config/loader.ts +80 -0
- package/src/common/context.ts +156 -0
- package/src/common/error/badrequesterror.ts +6 -0
- package/src/common/error/configfilenotfound.ts +6 -0
- package/src/common/error/forbiddenerror.ts +6 -0
- package/src/common/error/index.ts +6 -0
- package/src/common/error/notfound.ts +6 -0
- package/src/common/error/notimplemented.ts +6 -0
- package/src/common/error/unauthorizederror.ts +6 -0
- package/src/common/helpers.ts +11 -0
- package/src/common/index.ts +7 -0
- package/src/common/logger/common.ts +6 -0
- package/src/common/logger/factory.ts +51 -0
- package/src/common/logger/formatter.ts +9 -0
- package/src/common/logger/index.ts +6 -0
- package/src/common/logger/logger.ts +114 -0
- package/src/common/logger/transport.ts +71 -0
- package/src/common/router-helpers.ts +20 -0
- package/src/common/router-utils.ts +93 -0
- package/src/common/session/common.ts +37 -0
- package/src/common/session/index.ts +2 -0
- package/src/common/session/service.ts +157 -0
- package/src/common/tokenize-match.ts +152 -0
- package/src/index.ts +7 -0
- package/src/middleware/buffer.ts +80 -0
- package/src/middleware/cookie.ts +20 -0
- package/src/middleware/cors.ts +96 -0
- package/src/middleware/form.ts +59 -0
- package/src/middleware/group.ts +68 -0
- package/src/middleware/index.ts +47 -0
- package/src/middleware/json.ts +55 -0
- package/src/middleware/logger.ts +18 -0
- package/src/middleware/parse.ts +93 -0
- package/src/middleware/session.ts +136 -0
- package/src/middleware/tag.ts +15 -0
- package/src/middleware/text.ts +45 -0
- package/src/proxy.ts +59 -0
- package/src/router.ts +301 -0
- package/src/static.ts +231 -0
package/src/router.ts
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import {IncomingMessage, RequestListener} from "http";
|
|
2
|
+
import {v4} from "uuid";
|
|
3
|
+
import {Logger} from "./common/logger";
|
|
4
|
+
import {Context, ErrorHandler, Handler, Method} from "./common/context";
|
|
5
|
+
import {
|
|
6
|
+
HandlerWithOptions,
|
|
7
|
+
ResponseHandler,
|
|
8
|
+
ResultParser,
|
|
9
|
+
RouterHandlerOptions,
|
|
10
|
+
RouterJSONDoc
|
|
11
|
+
} from "./common/router-utils";
|
|
12
|
+
import {matchTokenizePath, normalizePath, PathPartToken, splitPath, tokenizePath} from "./common/tokenize-match";
|
|
13
|
+
import {defaultLoggerFactory} from "./common/router-helpers";
|
|
14
|
+
import {GroupPolicyHandler, ParseRequest, SessionHandler} from "./middleware";
|
|
15
|
+
import {parse, ParseOptionMap} from "@miqro/parser";
|
|
16
|
+
|
|
17
|
+
const ROUTE_OPTIONS: ParseOptionMap = {
|
|
18
|
+
name: "string?",
|
|
19
|
+
description: "string?",
|
|
20
|
+
policy: "GroupPolicy?",
|
|
21
|
+
response: {
|
|
22
|
+
type: "nested?",
|
|
23
|
+
nestedOptions: {
|
|
24
|
+
options: {
|
|
25
|
+
body: "boolean?|ParseOptions[]!?|string?"
|
|
26
|
+
},
|
|
27
|
+
mode: "no_extra"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
request: {
|
|
31
|
+
type: "nested?",
|
|
32
|
+
nestedOptions: {
|
|
33
|
+
options: {
|
|
34
|
+
headers: "ParseOptions[]!?",
|
|
35
|
+
query: "boolean?|ParseOptions[]!?|string?",
|
|
36
|
+
params: "boolean?|ParseOptions[]!?|string?",
|
|
37
|
+
body: "boolean?|ParseOptions[]!?|string?"
|
|
38
|
+
},
|
|
39
|
+
mode: "no_extra"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
class RouterHandler {
|
|
45
|
+
|
|
46
|
+
private readonly tokens: PathPartToken[];
|
|
47
|
+
private readonly handler: Array<Handler | Router>;
|
|
48
|
+
private readonly isRouter: boolean;
|
|
49
|
+
private readonly options?: RouterHandlerOptions;
|
|
50
|
+
|
|
51
|
+
public constructor(
|
|
52
|
+
handler: Array<Handler> | HandlerWithOptions | Handler | Router,
|
|
53
|
+
private readonly path: string | undefined,
|
|
54
|
+
private readonly method: Method | undefined,
|
|
55
|
+
options?: RouterHandlerOptions) {
|
|
56
|
+
this.tokens = tokenizePath(path);
|
|
57
|
+
|
|
58
|
+
if (options) {
|
|
59
|
+
options = parse(options, {
|
|
60
|
+
parser: "ParserInterface?",
|
|
61
|
+
middleware: "function[]!?",
|
|
62
|
+
session: "SessionHandlerOptions?|function?",
|
|
63
|
+
...ROUTE_OPTIONS
|
|
64
|
+
}, "no_extra", "options");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let handlers: Array<Handler | Router> = []
|
|
68
|
+
this.isRouter = handler instanceof Router;
|
|
69
|
+
|
|
70
|
+
if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
|
|
71
|
+
// HandlerWithOptions
|
|
72
|
+
if (options) {
|
|
73
|
+
throw new Error("bad arguments. cannot send options with HandlerWithOptions");
|
|
74
|
+
}
|
|
75
|
+
handler = parse(handler, {
|
|
76
|
+
handler: "function[]!",
|
|
77
|
+
parser: "ParserInterface?",
|
|
78
|
+
middleware: "function[]!?",
|
|
79
|
+
session: "SessionHandlerOptions?|function?",
|
|
80
|
+
...ROUTE_OPTIONS
|
|
81
|
+
}, "no_extra", "handler");
|
|
82
|
+
const realHandler = (handler as HandlerWithOptions).handler;
|
|
83
|
+
const newOptions = {
|
|
84
|
+
...(handler as HandlerWithOptions)
|
|
85
|
+
};
|
|
86
|
+
delete (newOptions as any).handler;
|
|
87
|
+
handler = realHandler;
|
|
88
|
+
this.options = newOptions;
|
|
89
|
+
} else {
|
|
90
|
+
this.options = options;
|
|
91
|
+
}
|
|
92
|
+
const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
|
|
93
|
+
|
|
94
|
+
if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
|
|
95
|
+
throw new Error("bad arguments");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (this.options && this.options.middleware) {
|
|
99
|
+
handlers = handlers.concat(this.options.middleware);
|
|
100
|
+
}
|
|
101
|
+
if (this.options && this.options.session) {
|
|
102
|
+
handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
|
|
103
|
+
}
|
|
104
|
+
if (this.options && this.options.policy) {
|
|
105
|
+
handlers.push(GroupPolicyHandler(this.options.policy));
|
|
106
|
+
}
|
|
107
|
+
if (this.options && this.options.request) {
|
|
108
|
+
handlers.push(ParseRequest(this.options.request, this.options.parser));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
handlers = handlers.concat(routeHandlers);
|
|
112
|
+
|
|
113
|
+
if (this.options && this.options.response) {
|
|
114
|
+
if (typeof this.options.response.body === "boolean" && this.options.response.body) {
|
|
115
|
+
(handlers as Handler[]).push(ResponseHandler());
|
|
116
|
+
} else if (this.options.response.body) {
|
|
117
|
+
(handlers as Handler[]).push(ResultParser(this.options.response.body, this.options.parser));
|
|
118
|
+
(handlers as Handler[]).push(ResponseHandler());
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
this.handler = handlers;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
|
|
125
|
+
const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
|
|
126
|
+
const nMethod = this.method ? this.method : "";
|
|
127
|
+
|
|
128
|
+
if (this.isRouter) {
|
|
129
|
+
const router: Router = this.handler[0] as Router;
|
|
130
|
+
router.getJSONDoc(doc, `${prePath}${nPath}`);
|
|
131
|
+
} else if (this.options) {
|
|
132
|
+
if (!doc[`${prePath}${nPath}`]) {
|
|
133
|
+
doc[`${prePath}${nPath}`] = {};
|
|
134
|
+
}
|
|
135
|
+
if (doc[`${prePath}${nPath}`][nMethod]) {
|
|
136
|
+
throw new Error("cannot create doc routes override each other");
|
|
137
|
+
}
|
|
138
|
+
doc[`${prePath}${nPath}`][nMethod] = {
|
|
139
|
+
description: this.options.description,
|
|
140
|
+
name: this.options.name,
|
|
141
|
+
identifier: `${prePath}${nPath}${this.options.name ? this.options.name : ""}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
|
|
142
|
+
policy: this.options.policy,
|
|
143
|
+
request: this.options.request ? {
|
|
144
|
+
body: this.options.request.body,
|
|
145
|
+
headers: this.options.request.headers,
|
|
146
|
+
params: this.options.request.params,
|
|
147
|
+
query: this.options.request.query,
|
|
148
|
+
} : undefined,
|
|
149
|
+
response: this.options.response
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
return doc;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
|
|
156
|
+
for (let i = 0; i < this.handler.length; i++) {
|
|
157
|
+
const h = this.handler[i];
|
|
158
|
+
if (h instanceof Router) {
|
|
159
|
+
if (!RouterHandler.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
} else {
|
|
163
|
+
if (!RouterHandler.pushResults(await h(ctx), ctx)) {
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
public isMatch(
|
|
172
|
+
method: string,
|
|
173
|
+
pathTokens: { value: string; lower: string; }[],
|
|
174
|
+
prePathTokens: PathPartToken[]): {
|
|
175
|
+
match: boolean;
|
|
176
|
+
params?: { [name: string]: string | undefined }
|
|
177
|
+
} {
|
|
178
|
+
if ((this.method === undefined || this.method === method)) {
|
|
179
|
+
if (this.path === undefined) {
|
|
180
|
+
return {
|
|
181
|
+
match: true
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
match: false
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private static pushResults(result: any, ctx: Context): boolean {
|
|
192
|
+
if (result === false) {
|
|
193
|
+
// ctx.logger.debug(`avoiding next handlers because handler returned false.`);
|
|
194
|
+
return false;
|
|
195
|
+
} else if (result !== true && result !== undefined) {
|
|
196
|
+
ctx.logger.trace("pushing to results [%o]", result);
|
|
197
|
+
ctx.results.push(result);
|
|
198
|
+
}
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface RouterOptions {
|
|
204
|
+
loggerFactory?: (uuid: string, req: IncomingMessage) => Logger;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export class Router {
|
|
208
|
+
protected readonly handlers: RouterHandler[] = [];
|
|
209
|
+
protected readonly errorHandlers: ErrorHandler[] = [];
|
|
210
|
+
public readonly listener: RequestListener;
|
|
211
|
+
|
|
212
|
+
constructor(protected config?: RouterOptions) {
|
|
213
|
+
const loggerFactory = this.config && this.config.loggerFactory ? this.config.loggerFactory : defaultLoggerFactory;
|
|
214
|
+
this.listener = async (req, res) => {
|
|
215
|
+
const uuid = v4().toString();
|
|
216
|
+
const logger = loggerFactory(uuid, req);
|
|
217
|
+
const ctx = new Context(uuid, req, res, logger);
|
|
218
|
+
ctx.logger.trace(`request received`);
|
|
219
|
+
await this.run(ctx);
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
public get(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
224
|
+
return this.use(handler, path, "get", options);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
public post(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
228
|
+
return this.use(handler, path, "post", options);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
public patch(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
232
|
+
return this.use(handler, path, "patch", options);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
public delete(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
236
|
+
return this.use(handler, path, "delete", options);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
public put(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
240
|
+
return this.use(handler, path, "put", options);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
public options(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
244
|
+
return this.use(handler, path, "options", options);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
public use(handler: Array<Handler> | HandlerWithOptions | Handler | Router, path?: string, method?: Method, options?: RouterHandlerOptions): Router {
|
|
248
|
+
const nPath = path !== undefined ? normalizePath(path) : undefined;
|
|
249
|
+
const nMethod = method ? method.toUpperCase() as Method : method;
|
|
250
|
+
this.handlers.push(new RouterHandler(handler, nPath, nMethod, options));
|
|
251
|
+
return this;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
|
|
255
|
+
const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
|
|
256
|
+
for (const e of errorHandlers) {
|
|
257
|
+
this.errorHandlers.push(e);
|
|
258
|
+
}
|
|
259
|
+
return this;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
263
|
+
pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
|
|
264
|
+
try {
|
|
265
|
+
for (const h of this.handlers) {
|
|
266
|
+
if (ctx.res.headersSent) {
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
const isMatch = h.isMatch(ctx.method, pathTokens, prePathTokens);
|
|
270
|
+
if (isMatch.match) {
|
|
271
|
+
if (isMatch.params) {
|
|
272
|
+
ctx.params = ctx.params ? {
|
|
273
|
+
...ctx.params,
|
|
274
|
+
...isMatch.params
|
|
275
|
+
} : isMatch.params;
|
|
276
|
+
}
|
|
277
|
+
const shouldContinue = await h.invoke(ctx, pathTokens, prePathTokens);
|
|
278
|
+
if (!shouldContinue) {
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return !ctx.res.headersSent;
|
|
284
|
+
} catch (e: any) {
|
|
285
|
+
for (const eH of this.errorHandlers) {
|
|
286
|
+
const ret = await eH(e, ctx);
|
|
287
|
+
if (ret === false || ctx.res.headersSent) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
throw e; // pass the error along
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
|
|
296
|
+
for (const h of this.handlers) {
|
|
297
|
+
doc = h.getJSONDoc(doc, prePath);
|
|
298
|
+
}
|
|
299
|
+
return doc;
|
|
300
|
+
}
|
|
301
|
+
}
|
package/src/static.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import {existsSync, readdirSync, readFileSync, statSync} from "fs";
|
|
2
|
+
import {extname, resolve} from "path";
|
|
3
|
+
import {Context} from "./common/context";
|
|
4
|
+
import {parse} from "@miqro/parser";
|
|
5
|
+
import {PathPartToken} from "./common/tokenize-match";
|
|
6
|
+
import {Router, RouterOptions} from "./router";
|
|
7
|
+
|
|
8
|
+
const outputFile = async (path: string, contentType: string, ctx: Context, allowGetJSON: boolean) => {
|
|
9
|
+
const buffer = readFileSync(path);
|
|
10
|
+
return allowGetJSON && ctx.query.format && ctx.query.format === "json" ?
|
|
11
|
+
ctx.json({
|
|
12
|
+
buffer
|
|
13
|
+
}) :
|
|
14
|
+
ctx.end({
|
|
15
|
+
status: 200,
|
|
16
|
+
headers: {
|
|
17
|
+
["Content-Type"]: contentType
|
|
18
|
+
},
|
|
19
|
+
body: buffer
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const generateList = async (path: string, ctx: Context, allowListJSON: boolean) => {
|
|
24
|
+
const files = readdirSync(path);
|
|
25
|
+
return allowListJSON && ctx.query.format && ctx.query.format === "json" ?
|
|
26
|
+
ctx.json({files: files.map(f => `${ctx.path}${f}`)}) :
|
|
27
|
+
ctx.html(`<html><body><ul>${files.map(f => `<li><a href="${ctx.path}${f}">${f}</a></li>`).join("")}</ul></body></html>`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface StaticRouterOptions extends RouterOptions {
|
|
31
|
+
directory: string;
|
|
32
|
+
list?: boolean;
|
|
33
|
+
allowListJSON?: boolean;
|
|
34
|
+
allowGetJSON?: boolean;
|
|
35
|
+
index?: string;
|
|
36
|
+
index404?: string;
|
|
37
|
+
contentTypes?: any;
|
|
38
|
+
defaultContentType?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function Static(options: StaticRouterOptions): Router {
|
|
42
|
+
return new StaticRouter(options);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
class StaticRouter extends Router {
|
|
46
|
+
|
|
47
|
+
private readonly staticOptions: {
|
|
48
|
+
directory: string;
|
|
49
|
+
list: boolean;
|
|
50
|
+
allowListJSON: boolean;
|
|
51
|
+
allowGetJSON: boolean;
|
|
52
|
+
index: string;
|
|
53
|
+
index404: string;
|
|
54
|
+
contentTypes: any;
|
|
55
|
+
defaultContentType: string;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
constructor(options: StaticRouterOptions) {
|
|
59
|
+
super(options);
|
|
60
|
+
this.staticOptions = parse(options, {
|
|
61
|
+
loggerFactory: {
|
|
62
|
+
required: false,
|
|
63
|
+
type: "any"
|
|
64
|
+
},
|
|
65
|
+
directory: {
|
|
66
|
+
type: "string",
|
|
67
|
+
required: true
|
|
68
|
+
},
|
|
69
|
+
list: {
|
|
70
|
+
type: "boolean",
|
|
71
|
+
required: false,
|
|
72
|
+
defaultValue: false
|
|
73
|
+
},
|
|
74
|
+
allowListJSON: {
|
|
75
|
+
type: "boolean",
|
|
76
|
+
required: false,
|
|
77
|
+
defaultValue: false
|
|
78
|
+
},
|
|
79
|
+
allowGetJSON: {
|
|
80
|
+
type: "boolean",
|
|
81
|
+
required: false,
|
|
82
|
+
defaultValue: false
|
|
83
|
+
},
|
|
84
|
+
index: {
|
|
85
|
+
type: "string",
|
|
86
|
+
required: false,
|
|
87
|
+
defaultValue: "index.html"
|
|
88
|
+
},
|
|
89
|
+
index404: {
|
|
90
|
+
type: "string",
|
|
91
|
+
required: false
|
|
92
|
+
},
|
|
93
|
+
contentTypes: {
|
|
94
|
+
type: "object",
|
|
95
|
+
required: false,
|
|
96
|
+
defaultValue: {
|
|
97
|
+
".aac": "audio/aac",
|
|
98
|
+
".abw": "application/x-abiword",
|
|
99
|
+
".arc": "application/x-freearc",
|
|
100
|
+
".avif": "image/avif",
|
|
101
|
+
".avi": "video/x-msvideo",
|
|
102
|
+
".azw": "application/vnd.amazon.ebook",
|
|
103
|
+
".bin": "application/octet-stream",
|
|
104
|
+
".bmp": "image/bmp",
|
|
105
|
+
".bz": "application/x-bzip",
|
|
106
|
+
".bz2": "application/x-bzip2",
|
|
107
|
+
".cda": "application/x-cdf",
|
|
108
|
+
".csh": "application/x-csh",
|
|
109
|
+
".css": "text/css",
|
|
110
|
+
".csv": "text/csv",
|
|
111
|
+
".doc": "application/msword",
|
|
112
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
113
|
+
".eot": "application/vnd.ms-fontobject",
|
|
114
|
+
".epub": "application/epub+zip",
|
|
115
|
+
".gz": "application/gzip",
|
|
116
|
+
".gif": "image/gif",
|
|
117
|
+
".htm": "text/html",
|
|
118
|
+
".html": "text/html",
|
|
119
|
+
".ico": "image/vnd.microsoft.icon",
|
|
120
|
+
".ics": "text/calendar",
|
|
121
|
+
".jar": "application/java-archive",
|
|
122
|
+
".jpeg": "image/jpeg",
|
|
123
|
+
".jpg": "image/jpeg",
|
|
124
|
+
".js": "text/javascript",
|
|
125
|
+
".json": "application/json",
|
|
126
|
+
".jsonld": "application/ld+json",
|
|
127
|
+
".mid": "audio/midi audio/x-midi",
|
|
128
|
+
".midi": "audio/midi audio/x-midi",
|
|
129
|
+
".mjs": "text/javascript",
|
|
130
|
+
".mp3": "audio/mpeg",
|
|
131
|
+
".mp4": "video/mp4",
|
|
132
|
+
".mpeg": "video/mpeg",
|
|
133
|
+
".mpkg": "application/vnd.apple.installer+xml",
|
|
134
|
+
".odp": "application/vnd.oasis.opendocument.presentation",
|
|
135
|
+
".ods": "application/vnd.oasis.opendocument.spreadsheet",
|
|
136
|
+
".odt": "application/vnd.oasis.opendocument.text",
|
|
137
|
+
".oga": "audio/ogg",
|
|
138
|
+
".ogv": "video/ogg",
|
|
139
|
+
".ogx": "application/ogg",
|
|
140
|
+
".opus": "audio/opus",
|
|
141
|
+
".otf": "font/otf",
|
|
142
|
+
".png": "image/png",
|
|
143
|
+
".pdf": "application/pdf",
|
|
144
|
+
".php": "application/x-httpd-php",
|
|
145
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
146
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
147
|
+
".rar": "application/vnd.rar",
|
|
148
|
+
".rtf": "application/rtf",
|
|
149
|
+
".sh": "application/x-sh",
|
|
150
|
+
".svg": "image/svg+xml",
|
|
151
|
+
".swf": "application/x-shockwave-flash",
|
|
152
|
+
".tar": "application/x-tar",
|
|
153
|
+
".tif": "image/tiff",
|
|
154
|
+
".tiff": "image/tiff",
|
|
155
|
+
".ts": "video/mp2t",
|
|
156
|
+
".ttf": "font/ttf",
|
|
157
|
+
".txt": "text/plain",
|
|
158
|
+
".vsd": "application/vnd.visio",
|
|
159
|
+
".wav": "audio/wav",
|
|
160
|
+
".weba": "audio/webm",
|
|
161
|
+
".webm": "video/webm",
|
|
162
|
+
".webp": "image/webp",
|
|
163
|
+
".woff": "font/woff",
|
|
164
|
+
".woff2": "font/woff2",
|
|
165
|
+
".xhtml": "application/xhtml+xml",
|
|
166
|
+
".xls": "application/vnd.ms-excel",
|
|
167
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
168
|
+
".xml": "application/xml",
|
|
169
|
+
".xul": "application/vnd.mozilla.xul+xml",
|
|
170
|
+
".zip": "application/zip",
|
|
171
|
+
".3gp": "video/3gpp; audio/3gpp",
|
|
172
|
+
".3g2": "video/3gpp2; audio/3gpp2",
|
|
173
|
+
".7z": "application/x-7z-compressed"
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
defaultContentType: {
|
|
177
|
+
type: "string",
|
|
178
|
+
required: false,
|
|
179
|
+
defaultValue: "application/octet-stream"
|
|
180
|
+
}
|
|
181
|
+
}, "no_extra", "options");
|
|
182
|
+
if (!statSync(this.staticOptions.directory).isDirectory()) {
|
|
183
|
+
throw new Error(`options.directory ${this.staticOptions.directory} not a directory`);
|
|
184
|
+
}
|
|
185
|
+
if (this.staticOptions.index404 && !existsSync(resolve(this.staticOptions.directory, this.staticOptions.index404))) {
|
|
186
|
+
throw new Error(`options.index404 ${this.staticOptions.index404} not a found`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
191
|
+
const {directory, allowGetJSON, allowListJSON, list, index, contentTypes, defaultContentType} = this.staticOptions;
|
|
192
|
+
const level = prePathTokens.length;
|
|
193
|
+
if (ctx.method === "GET") {
|
|
194
|
+
const realPath = resolve(directory, ctx.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/"));
|
|
195
|
+
ctx.logger.debug("static get %s", realPath);
|
|
196
|
+
|
|
197
|
+
if (existsSync(realPath)) {
|
|
198
|
+
if (statSync(realPath).isDirectory()) {
|
|
199
|
+
// directory
|
|
200
|
+
const indexPath = resolve(realPath, index);
|
|
201
|
+
if (index && existsSync(indexPath) && statSync(indexPath).isFile()) {
|
|
202
|
+
// index file exists
|
|
203
|
+
const ext = extname(indexPath);
|
|
204
|
+
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
205
|
+
await outputFile(indexPath, contentType, ctx, allowGetJSON);
|
|
206
|
+
} else {
|
|
207
|
+
// index doesn't exists
|
|
208
|
+
if (list) {
|
|
209
|
+
// generate list
|
|
210
|
+
await generateList(realPath, ctx, allowListJSON);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
// direct file access
|
|
215
|
+
const ext = extname(realPath);
|
|
216
|
+
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
217
|
+
await outputFile(realPath, contentType, ctx, allowGetJSON);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if(this.staticOptions.index404) {
|
|
222
|
+
const realPath = resolve(this.staticOptions.directory, this.staticOptions.index404);
|
|
223
|
+
if (existsSync(realPath)) {
|
|
224
|
+
const ext = extname(realPath);
|
|
225
|
+
const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
|
|
226
|
+
await outputFile(realPath, contentType, ctx, allowGetJSON);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return !ctx.res.headersSent ? super.run(ctx, pathTokens, prePathTokens) : false;
|
|
230
|
+
}
|
|
231
|
+
}
|