@miqro/core 5.0.10 → 5.0.12

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.
@@ -36,7 +36,7 @@ import { ServerOptions } from "http";
36
36
  import { SessionHandler, GroupPolicyHandler } from "./session.js";
37
37
  import { DEFAULT_PARSER, assertNotUndefined, ResponseHandler, ResultParser, ParseRequest } from "./body-parser.js";
38
38
  import { RequestOptions, request } from "@miqro/request";
39
- import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "fs";
39
+ import { existsSync, fstatSync, lstatSync, readFileSync, readdirSync, statSync } from "fs";
40
40
  import { basename, extname, join, parse, resolve } from "path";
41
41
 
42
42
  /**
@@ -61,6 +61,11 @@ export class Router implements MinimalRouter {
61
61
  };
62
62
  }
63
63
 
64
+ public clear() {
65
+ this.handlers.splice(0, this.handlers.length);
66
+ this.errorHandlers.splice(0, this.errorHandlers.length);
67
+ }
68
+
64
69
  public get(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
65
70
  return this.use(handler, path, "get", options);
66
71
  }
@@ -150,14 +155,15 @@ export class Router implements MinimalRouter {
150
155
  return doc;
151
156
  }
152
157
 
153
- public logPaths(logger: MinimalLogger): void {
154
- this.toString().split("\n").forEach(l => logger.info(l));
158
+ public logPaths(logger: MinimalLogger, filter?: (path: string, method: string) => boolean): void {
159
+ this.toString(filter).split("\n").forEach(l => logger.info(l));
155
160
  }
156
161
 
157
- public toString(): string {
162
+ public toString(filter?: (path: string, method: string) => boolean): string {
158
163
  let ret = "";
159
164
  const doc = this.getJSONDoc();
160
165
  const paths = Object.keys(doc);
166
+ const tab = " ";
161
167
 
162
168
  for (const path of paths) {
163
169
  if (path) {
@@ -167,9 +173,12 @@ export class Router implements MinimalRouter {
167
173
 
168
174
  for (const method of methods) {
169
175
  if (method) {
170
- const methodDataList = pathData[method];
171
- for (const methodData of methodDataList) {
172
- ret += `${ret === "" ? "" : "\n"}${String(method).toUpperCase()}:${path}\n\t${methodData.identifier}${methodData.name ? `\n\t\t${methodData.name}` : ""}${methodData.description ? `\n\t\t${methodData.description}` : ""}`;
176
+ const show = filter ? filter(path, method) : true;
177
+ if (show) {
178
+ const methodDataList = pathData[method];
179
+ for (const methodData of methodDataList) {
180
+ ret += `${ret === "" ? "" : "\n"}${String(method).toUpperCase()}:${path}\n${tab}${methodData.identifier}${methodData.name ? `\n${tab}${tab}${methodData.name}` : ""}${methodData.description ? `\n${tab}${tab}${methodData.description}` : ""}`;
181
+ }
173
182
  }
174
183
  }
175
184
  }
@@ -739,7 +748,7 @@ export async function APIRouter(options: APIRouterOptions, logger?: Logger): Pro
739
748
  }
740
749
  const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
741
750
  const apiPath = options.path !== undefined ? options.path : "";
742
- return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger, options.ignore);
751
+ return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger, options.ignore, options.loader, options.extensions);
743
752
  }
744
753
 
745
754
  type UseCallArg = [Handler | Handler[] | MinimalRouter, string | undefined, Method | undefined, RouterHandlerOptions];
@@ -758,26 +767,29 @@ function isIgnored(f: string, ignore?: Array<string | RegExp>): boolean {
758
767
  return false;
759
768
  }
760
769
 
770
+ const DEFAULTAPIValidExtensions = new Set([".mjsx", ".mts", ".mjs", ".tsx", ".jsx", ".ts", ".js"]);
771
+
761
772
  async function traverseAPIRouteDir(
762
773
  featureName: string,
763
774
  dirname: string,
764
775
  basePath = "/",
765
- router: Router = new Router(), logger?: Logger, ignore?: Array<string | RegExp>): Promise<Router> {
776
+ router: Router = new Router(), logger?: Logger, ignore?: Array<string | RegExp>, importFN?: (path: string) => Promise<any>, extensions?: string[]): Promise<Router> {
766
777
  if (logger) {
767
778
  logger.trace("loading routes from [%s]", dirname);
768
779
  }
780
+ const VALID_EXTENSION = extensions ? new Set(extensions) : DEFAULTAPIValidExtensions;
769
781
  const files = readdirSync(dirname).filter(f => !isIgnored(f, ignore));
770
- const dirs = files.filter(f => lstatSync(join(dirname, f)).isDirectory());
771
- const methods = files.filter(f => !lstatSync(join(dirname, f)).isDirectory());
782
+ const dirs = files.filter(f => statSync(join(dirname, f)).isDirectory());
783
+ const methods = files.filter(f => !statSync(join(dirname, f)).isDirectory());
772
784
 
773
785
  const postFolder: UseCallArg[] = [];
774
786
 
775
787
  for (const f of methods) {
776
788
  const { name, ext } = parse(f);
777
- if (name !== "index" && ((ext === ".ts" || ext === ".js") && name.slice(-2) !== ".d")) {
789
+ if (VALID_EXTENSION.has(ext) && name.slice(-2) !== ".d") {
778
790
  const filePath = join(dirname, f);
779
791
  //console.log("dirname=%s f=%s", dirname, f);
780
- let route: APIRoute = await import(filePath);
792
+ let route: APIRoute = importFN ? await importFN(filePath) : await import(filePath);
781
793
  //if ((route as any).default && (route as any).__esModule === true) {
782
794
  if ((route as any).default) {
783
795
  route = (route as any).default;
@@ -789,19 +801,19 @@ async function traverseAPIRouteDir(
789
801
  //const ___filePath = filePath + ext;
790
802
  const ___filePath = filePath;
791
803
  //let routeMethods: Method[] = [name] as Method[];
792
- let routeMethod: Method | "use" | "USE" = name as Method;
804
+ let routeMethod: Method[] | Method | "use" | "USE" = name as Method;
793
805
  if (typeof route === "function") {
794
806
  route = {
795
807
  handler: route
796
808
  } as any;
797
809
  } else {
798
- if (typeof route.method !== "undefined" && (/*!(route.method instanceof Array) &&*/ (typeof route.method !== "string"))) {
810
+ if (typeof route.method !== "undefined" && (!(route.method instanceof Array) && (typeof route.method !== "string"))) {
799
811
  //throw new Error(`${resolve(dirname, name)} doesn't export method as a string or string array`);
800
812
  throw new Error(`${resolve(dirname, name)} doesnt export method as a string`);
801
813
  } else if (typeof route.method !== "undefined") {
802
814
  routeMethod = route.method;//route.method instanceof Array ? route.method : [route.method];
803
815
  }
804
- if (typeof route.path !== "string" && typeof route.path !== "undefined" && route.path !== null/* && !(route.path instanceof Array)*/) {
816
+ if (typeof route.path !== "string" && typeof route.path !== "undefined" && route.path !== null && !(route.path instanceof Array)) {
805
817
  //throw new Error(`${resolve(dirname, name)} doesn't export path as a string or a string array`);
806
818
  throw new Error(`${resolve(dirname, name)} doesnt export path as a string`);
807
819
  }
@@ -821,37 +833,54 @@ async function traverseAPIRouteDir(
821
833
  if (route.ignore !== undefined && route.ignore === true) {
822
834
  continue;
823
835
  }
824
- const p = route.path === undefined ? route.method && route.method.indexOf(name as Method) === -1 ? `/${name}` : "/" : route.path;
825
- if (p !== null && (typeof p !== "string" || !p)) {
826
- throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
836
+ //console.dir(route);
837
+ if (route.init) {
838
+ await route.init(route);
827
839
  }
828
- const path = p === null ? undefined : normalizePath(`${basePath}${p && p !== "/" ? `${p}` : p}`)
840
+ //console.dir(route);
841
+ const p = route.path === undefined ?
842
+ route.method && route.method.indexOf(name as Method) === -1 ?
843
+ `${name}` : "/"
844
+ : route.path;
829
845
 
830
- if (route.identifier && route.identifier === "__prototype__" || route.identifier === "__proto__") {
831
- throw new Error(`invalid feature name ${route.identifier}`);
832
- }
833
- const useCallArgs: UseCallArg = [route.handler, path, routeMethod !== "use" && routeMethod !== "USE" ? routeMethod : undefined, {
834
- identifier: route.identifier,
835
- apiName: route.apiName,
836
- name: route.name,
837
- description: route.description,
838
- parser: route.parser,
839
- middleware: route.middleware,
840
- session: route.session,
841
- policy: route.policy,
842
- request: route.request,
843
- response: route.response !== undefined ? route.response : true // ResponseHandler added by default to an APIRoute
844
- }];
845
- if (route.postFolder) {
846
- postFolder.push(useCallArgs);
847
- } else {
848
- router.use(...useCallArgs);
846
+ /*if (p !== null && (typeof p !== "string" && !p)) {
847
+ throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
848
+ }*/
849
+ const paths = p instanceof Array ? p : [p];
850
+ const methods = routeMethod instanceof Array ? routeMethod : [routeMethod];
851
+
852
+ for (const method of methods) {
853
+ for (const pathsP of paths) {
854
+ const path = pathsP === null ? undefined : normalizePath(`${basePath}${pathsP && pathsP !== "/" ? `/${pathsP}` : pathsP}`)
855
+
856
+ if (route.identifier && route.identifier === "__prototype__" || route.identifier === "__proto__") {
857
+ throw new Error(`invalid feature name ${route.identifier}`);
858
+ }
859
+ const useCallArgs: UseCallArg = [route.handler, path, method !== "use" && method !== "USE" ? method : undefined, {
860
+ identifier: route.identifier,
861
+ apiName: route.apiName,
862
+ name: route.name,
863
+ description: route.description,
864
+ parser: route.parser,
865
+ middleware: route.middleware,
866
+ session: route.session,
867
+ policy: route.policy,
868
+ request: route.request,
869
+ response: route.response !== undefined ? route.response : true // ResponseHandler added by default to an APIRoute
870
+ }];
871
+ //console.dir(useCallArgs);
872
+ if (route.postFolder) {
873
+ postFolder.push(useCallArgs);
874
+ } else {
875
+ router.use(...useCallArgs);
876
+ }
877
+ }
849
878
  }
850
879
  }
851
880
  }
852
881
  for (const f of dirs) {
853
882
  const { name } = parse(f);
854
- router = await traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, router, logger, ignore);
883
+ router = await traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, router, logger, ignore, importFN, extensions);
855
884
  }
856
885
  for (const post of postFolder) {
857
886
  router.use(...post);
@@ -3,16 +3,17 @@ import { RequestOptions, RequestResponse, request } from "@miqro/request";
3
3
  import { Schema } from "@miqro/parser";
4
4
  import { parse as cookieParse } from "cookie";
5
5
  import { BadRequestError, checkEnvVariables, ForbiddenError, UnAuthorizedError } from "../common.js";
6
- import { GroupPolicy, GroupPolicySchema, Handler, NoTokenSession, Request, Response, Session, SessionHandlerOptions } from "../types.js";
6
+ import { GroupPolicy, GroupPolicySchema, Handler, NoTokenSession, Request, Response, Session, SessionHandlerOptions, SessionHandlerOptionsOptionsSchema, SessionHandlerOptionsSchema } from "../types.js";
7
7
 
8
- const DEFAULT_TOKEN_LOCATION = "header";
8
+ //const DEFAULT_TOKEN_LOCATION = "header";
9
+ const DEFAULT_TOKEN_LOCATION = "free";
9
10
  const DEFAULT_TOKEN_HEADER = "Authorization";
10
11
  const DEFAULT_TOKEN_QUERY = "token";
11
12
  const DEFAULT_TOKEN_COOKIE = "Authorization";
12
- const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
13
- const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
14
- const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
15
- const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
13
+ export const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
14
+ export const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
15
+ export const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
16
+ export const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
16
17
 
17
18
  export interface VerifyTokenService {
18
19
  verify(args: { token: string; req: Request }): Promise<Session | null>;
@@ -92,7 +93,7 @@ export class VerifyEndpointService implements VerifyTokenService {
92
93
  switch (tokenVerifyLocation) {
93
94
  case "header":
94
95
  const tokenHeaderLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
95
- req.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_HEADER=[${tokenHeaderLocation}]`);
96
+ req.logger.debug(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_HEADER=[${tokenHeaderLocation}]`);
96
97
  response = await this.getResponse({
97
98
  url,
98
99
  headers: {
@@ -103,7 +104,7 @@ export class VerifyEndpointService implements VerifyTokenService {
103
104
  break;
104
105
  case "query":
105
106
  const tokenQueryLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
106
- req.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_QUERY=[${tokenQueryLocation}]`);
107
+ req.logger.debug(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_QUERY=[${tokenQueryLocation}]`);
107
108
  response = await this.getResponse({
108
109
  url,
109
110
  query: {
@@ -114,7 +115,7 @@ export class VerifyEndpointService implements VerifyTokenService {
114
115
  break;
115
116
  case "cookie":
116
117
  const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
117
- req.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_COOKIE=[${tokenCookieLocation}]`);
118
+ req.logger.debug(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_COOKIE=[${tokenCookieLocation}]`);
118
119
  response = await this.getResponse({
119
120
  url,
120
121
  method,
@@ -132,7 +133,7 @@ export class VerifyEndpointService implements VerifyTokenService {
132
133
  req.logger.warn(`unauthorized token not valid [${token}]`);
133
134
  return null;
134
135
  } else {
135
- req.logger.trace("token [%s]authorized!", token);
136
+ req.logger.debug("token [%s]authorized!", token);
136
137
 
137
138
  if (tokenVerifyLocation === "cookie" && response.headers["set-cookie"]) {
138
139
  const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
@@ -191,6 +192,8 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
191
192
  }
192
193
  };
193
194
  switch (tokenLocation) {
195
+ case "free":
196
+ break;
194
197
  case "header":
195
198
  config.options.tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
196
199
  break;
@@ -213,44 +216,15 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
213
216
  throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header or query)`);
214
217
  }
215
218
  } else {
216
- config.options = assertNotUndefined(DEFAULT_PARSER.parse(config.options as any, {
217
- type: "object",
218
- properties: {
219
- tokenLocation: {
220
- required: true,
221
- type: "enum",
222
- enumValues: ["header", "query", "cookie"]
223
- },
224
- tokenLocationName: {
225
- required: true,
226
- type: "any"
227
- },
228
- setCookieOptions: {
229
- required: false,
230
- type: "object",
231
- defaultValue: {
232
- httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
233
- secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
234
- path: DEFAULT_TOKEN_SET_COOKIE_PATH,
235
- sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE,
236
- },
237
- properties: {
238
- httpOnly: "boolean",
239
- secure: "boolean",
240
- path: "any",
241
- sameSite: {
242
- required: true, type: "enum", enumValues: ["lax", "strict", "none"]
243
- }
244
- }
245
- }
246
- }
247
- }, "options"), "bad options");
219
+ config.options = assertNotUndefined(DEFAULT_PARSER.parse(config.options as any, SessionHandlerOptionsOptionsSchema, "options"), "bad options");
248
220
  }
249
221
 
250
222
  if (!config.authService) {
251
223
  throw new Error("authService must be provided!");
252
224
  }
253
225
  if (!config.options || !config.options.setCookieOptions) {
226
+ console.dir(config);
227
+ process.exit(1);
254
228
  throw new Error("config.options not populated!");
255
229
  }
256
230
  const tokenLocation = config.options.tokenLocation;
@@ -258,12 +232,15 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
258
232
  const setCookieOptions = config.options.setCookieOptions;
259
233
  return async function SessionHandler(req, res): Promise<void> {
260
234
  try {
261
- const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(req);
235
+ const tlN = typeof tokenLocationName === "string" ? tokenLocationName : tokenLocationName ? await tokenLocationName(req) : "";
262
236
  let token = null;
263
237
  switch (tokenLocation) {
264
238
  case "header":
265
239
  token = req.headers[(tlN).toLowerCase()] as string;
266
240
  break;
241
+ case "free":
242
+ token = null;
243
+ break;
267
244
  case "query":
268
245
  token = req.query[tlN] as string;
269
246
  break;
@@ -273,7 +250,7 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
273
250
  default:
274
251
  throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
275
252
  }
276
- if (!token) {
253
+ if (!token && tokenLocation !== "free") {
277
254
  req.logger.warn("No token provided!");
278
255
  throw new ForbiddenError("NO TOKEN");
279
256
  } else {
package/src/types.ts CHANGED
@@ -5,6 +5,7 @@ import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
5
5
  import { Socket } from "net";
6
6
  import { Duplex } from "stream";
7
7
  import { Logger } from "./common.js";
8
+ import { DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY, DEFAULT_TOKEN_SET_COOKIE_PATH, DEFAULT_TOKEN_SET_COOKIE_SAME_SITE, DEFAULT_TOKEN_SET_COOKIE_SECURE } from "./middleware/session.js";
8
9
 
9
10
  /**
10
11
  * Types
@@ -31,6 +32,7 @@ export type LogLevel = "error" | "warn" | "info" | "debug" | "trace" | "none";
31
32
  export interface WriteArgs {
32
33
  level: LogLevel;
33
34
  message?: any;
35
+ identifier: string;
34
36
  optionalParams: any[]
35
37
  }
36
38
 
@@ -87,16 +89,48 @@ export const GroupPolicySchema: Schema<GroupPolicy> = {
87
89
 
88
90
  export interface SessionHandlerOptions {
89
91
  authService: {
90
- verify(args: { token: string; req: Request; res: Response }): Promise<Session | null>;
92
+ verify(args: { token?: string | null; req: Request; res: Response }): Promise<Session | null>;
91
93
  };
92
- options?: {
93
- tokenLocation: "header" | "query" | "cookie";
94
- tokenLocationName: string | ((req: Request) => Promise<string>);
95
- setCookieOptions?: {
96
- httpOnly: boolean;
97
- secure: boolean;
98
- path: string | ((req: Request) => Promise<string>);
99
- sameSite: "lax" | "strict" | "none";
94
+ options?: SessionHandlerOptionsOptions;
95
+ }
96
+
97
+ export interface SessionHandlerOptionsOptions {
98
+ tokenLocation: "header" | "query" | "cookie" | "free";
99
+ tokenLocationName?: string | ((req: Request) => Promise<string>);
100
+ setCookieOptions?: {
101
+ httpOnly: boolean;
102
+ secure: boolean;
103
+ path: string | ((req: Request) => Promise<string>);
104
+ sameSite: "lax" | "strict" | "none";
105
+ }
106
+ }
107
+
108
+ export const SessionHandlerOptionsOptionsSchema: Schema<SessionHandlerOptionsOptions> = {
109
+ type: "object",
110
+ properties: {
111
+ tokenLocation: {
112
+ type: "enum",
113
+ defaultValue: "free",
114
+ enumValues: ["header", "query", "cookie", "free"]
115
+ },
116
+ tokenLocationName: "string?|function?",
117
+ setCookieOptions: {
118
+ type: "object?",
119
+ defaultValue: Object.freeze({
120
+ httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
121
+ secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
122
+ path: DEFAULT_TOKEN_SET_COOKIE_PATH,
123
+ sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE
124
+ }),
125
+ properties: {
126
+ httpOnly: "boolean",
127
+ secure: "boolean",
128
+ path: "string|function",
129
+ sameSite: {
130
+ type: "enum",
131
+ enumValues: ["lax", "strict", "none"]
132
+ }
133
+ }
100
134
  }
101
135
  }
102
136
  }
@@ -112,25 +146,7 @@ export const SessionHandlerOptionsSchema: Schema<SessionHandlerOptions> = {
112
146
  },
113
147
  options: {
114
148
  type: "object?",
115
- properties: {
116
- tokenLocation: {
117
- type: "enum",
118
- enumValues: ["header", "query", "cookie"]
119
- },
120
- tokenLocationName: "string|function",
121
- setCookieOptions: {
122
- type: "object?",
123
- properties: {
124
- httpOnly: "boolean",
125
- secure: "boolean",
126
- path: "string|function",
127
- sameSite: {
128
- type: "enum",
129
- enumValues: ["lax", "strict", "none"]
130
- }
131
- }
132
- }
133
- }
149
+ properties: SessionHandlerOptionsOptionsSchema.properties
134
150
  }
135
151
  }
136
152
  };
@@ -348,11 +364,13 @@ export function isMinimalRouter(obj: any) {
348
364
  * ```
349
365
  */
350
366
  export interface APIRoute extends RouterHandlerOptions {
351
- postFolder?: boolean,
352
- method?: Method | "use" | "USE";
353
- path?: string | null;
367
+ postFolder?: boolean;
368
+ basePath?: string;
369
+ method?: Method[] | Method | "use" | "USE";
370
+ path?: string[] | string | null;
354
371
  ignore?: boolean;
355
372
  handler: Handler | Array<Handler> | MinimalRouter;
373
+ init?: (route: APIRoute) => Promise<void>;
356
374
  }
357
375
 
358
376
  export interface APIRouterOptions {
@@ -360,6 +378,8 @@ export interface APIRouterOptions {
360
378
  apiName?: string;
361
379
  path?: string;
362
380
  ignore?: Array<string | RegExp>;
381
+ loader?: (path: string) => Promise<any>;
382
+ extensions?: string[];
363
383
  }
364
384
 
365
385
  export const APIRouterOptionsSchema: Schema<APIRouterOptions> = {
@@ -371,7 +391,9 @@ export const APIRouterOptionsSchema: Schema<APIRouterOptions> = {
371
391
  ignore: {
372
392
  type: "array?",
373
393
  arrayType: "string|RegExp"
374
- }
394
+ },
395
+ loader: "function?",
396
+ extensions: "string[]?",
375
397
  }
376
398
  };
377
399
 
@@ -380,9 +402,10 @@ export const APIRouteSchema: Schema<APIRoute> = {
380
402
  properties: {
381
403
  ...RouterHandlerOptionsSchema.properties,
382
404
  postFolder: "boolean?",
383
- method: "string?",
405
+ basePath: "string?",
406
+ method: "string?|string[]?",
384
407
  path: {
385
- type: "string?",
408
+ type: "string?|string[]?",
386
409
  allowNull: true
387
410
  },
388
411
  ignore: "boolean?",
@@ -390,7 +413,8 @@ export const APIRouteSchema: Schema<APIRoute> = {
390
413
  type: "function[]!|object",
391
414
  properties: MinimalRouterSchema.properties,
392
415
  mode: MinimalRouterSchema.mode
393
- }
416
+ },
417
+ init: "function?"
394
418
  }
395
419
  };
396
420
 
@@ -492,6 +516,8 @@ export interface Response<Request extends IncomingMessage = IncomingMessage> ext
492
516
  addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse;
493
517
  setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse;
494
518
  html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
519
+ css(css: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
520
+ js(js: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
495
521
  text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
496
522
  redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
497
523
  }
@@ -523,6 +549,26 @@ export class Response<Request extends IncomingMessage = IncomingMessage> extends
523
549
  body: html
524
550
  })
525
551
  }
552
+ async css(css: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
553
+ return this.asyncEnd({
554
+ status: status !== undefined ? status : 200,
555
+ headers: {
556
+ ['Content-Type']: 'text/css; charset=utf-8',
557
+ ...headers
558
+ },
559
+ body: css
560
+ })
561
+ }
562
+ async js(js: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
563
+ return this.asyncEnd({
564
+ status: status !== undefined ? status : 200,
565
+ headers: {
566
+ ['Content-Type']: 'text/javascript; charset=utf-8',
567
+ ...headers
568
+ },
569
+ body: js
570
+ })
571
+ }
526
572
  async text(text: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
527
573
  return this.asyncEnd({
528
574
  status: status !== undefined ? status : 200,
@@ -813,6 +859,7 @@ export interface WebSocketServerOptions {
813
859
  onConnection?: (req: WebSocketClient) => void;
814
860
  onMessage?: (req: WebSocketClient, data: string | undefined | null) => void;
815
861
  onDisconnect?: (req: WebSocketClient) => void;
862
+ onError?: (req: WebSocketClient, error: Error) => void;
816
863
  }
817
864
 
818
865
  export interface WebSocketClient {