@kaito-http/core 3.0.0-beta.1 → 3.0.0-beta.4
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/dist/index.d.ts +235 -0
- package/dist/index.js +389 -0
- package/package.json +18 -15
- package/dist/declarations/src/error.d.ts +0 -10
- package/dist/declarations/src/index.d.ts +0 -8
- package/dist/declarations/src/req.d.ts +0 -32
- package/dist/declarations/src/res.d.ts +0 -45
- package/dist/declarations/src/route.d.ts +0 -22
- package/dist/declarations/src/router.d.ts +0 -34
- package/dist/declarations/src/server.d.ts +0 -45
- package/dist/declarations/src/util.d.ts +0 -48
- package/dist/kaito-http-core.d.ts +0 -2
- package/dist/kaito-http-core.js +0 -534
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import * as find_my_way from 'find-my-way';
|
|
2
|
+
import find_my_way__default, { HTTPMethod } from 'find-my-way';
|
|
3
|
+
export { HTTPMethod } from 'find-my-way';
|
|
4
|
+
import * as http from 'http';
|
|
5
|
+
import * as http$1 from 'node:http';
|
|
6
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
7
|
+
import { CookieSerializeOptions } from 'cookie';
|
|
8
|
+
|
|
9
|
+
declare class WrappedError<T> extends Error {
|
|
10
|
+
readonly data: T;
|
|
11
|
+
static maybe<T>(maybeError: T): (T & Error) | WrappedError<T>;
|
|
12
|
+
static from<T>(data: T): WrappedError<T>;
|
|
13
|
+
private constructor();
|
|
14
|
+
}
|
|
15
|
+
declare class KaitoError extends Error {
|
|
16
|
+
readonly status: number;
|
|
17
|
+
constructor(status: number, message: string);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
declare class KaitoRequest {
|
|
21
|
+
readonly raw: IncomingMessage;
|
|
22
|
+
private _url;
|
|
23
|
+
constructor(raw: IncomingMessage);
|
|
24
|
+
/**
|
|
25
|
+
* The full URL of the request, including the protocol, hostname, and path.
|
|
26
|
+
* Note: does not include the query string or hash
|
|
27
|
+
*/
|
|
28
|
+
get fullURL(): string;
|
|
29
|
+
/**
|
|
30
|
+
* A new URL instance for the full URL of the request.
|
|
31
|
+
*/
|
|
32
|
+
get url(): URL;
|
|
33
|
+
/**
|
|
34
|
+
* The HTTP method of the request.
|
|
35
|
+
*/
|
|
36
|
+
get method(): HTTPMethod;
|
|
37
|
+
/**
|
|
38
|
+
* The protocol of the request, either `http` or `https`.
|
|
39
|
+
*/
|
|
40
|
+
get protocol(): 'http' | 'https';
|
|
41
|
+
/**
|
|
42
|
+
* The request headers
|
|
43
|
+
*/
|
|
44
|
+
get headers(): http.IncomingHttpHeaders;
|
|
45
|
+
/**
|
|
46
|
+
* The hostname of the request.
|
|
47
|
+
*/
|
|
48
|
+
get hostname(): string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
type ErroredAPIResponse = {
|
|
52
|
+
success: false;
|
|
53
|
+
data: null;
|
|
54
|
+
message: string;
|
|
55
|
+
};
|
|
56
|
+
type SuccessfulAPIResponse<T> = {
|
|
57
|
+
success: true;
|
|
58
|
+
data: T;
|
|
59
|
+
message: 'OK';
|
|
60
|
+
};
|
|
61
|
+
type APIResponse<T> = ErroredAPIResponse | SuccessfulAPIResponse<T>;
|
|
62
|
+
type AnyResponse = APIResponse<unknown>;
|
|
63
|
+
declare class KaitoResponse<T = unknown> {
|
|
64
|
+
readonly raw: ServerResponse;
|
|
65
|
+
constructor(raw: ServerResponse);
|
|
66
|
+
/**
|
|
67
|
+
* Send a response
|
|
68
|
+
* @param key The key of the header
|
|
69
|
+
* @param value The value of the header
|
|
70
|
+
* @returns The response object
|
|
71
|
+
*/
|
|
72
|
+
header(key: string, value: string | readonly string[]): this;
|
|
73
|
+
/**
|
|
74
|
+
* Set the status code of the response
|
|
75
|
+
* @param code The status code
|
|
76
|
+
* @returns The response object
|
|
77
|
+
*/
|
|
78
|
+
status(code: number): this;
|
|
79
|
+
/**
|
|
80
|
+
* Set a cookie
|
|
81
|
+
* @param name The name of the cookie
|
|
82
|
+
* @param value The value of the cookie
|
|
83
|
+
* @param options The options for the cookie
|
|
84
|
+
* @returns The response object
|
|
85
|
+
*/
|
|
86
|
+
cookie(name: string, value: string, options: CookieSerializeOptions): this;
|
|
87
|
+
/**
|
|
88
|
+
* Send a JSON APIResponse body
|
|
89
|
+
* @param data The data to send
|
|
90
|
+
* @returns The response object
|
|
91
|
+
*/
|
|
92
|
+
json(data: APIResponse<T>): this;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type Before<BeforeAfterContext> = (req: http$1.IncomingMessage, res: http$1.ServerResponse) => Promise<BeforeAfterContext>;
|
|
96
|
+
type HandlerResult = {
|
|
97
|
+
success: true;
|
|
98
|
+
data: unknown;
|
|
99
|
+
} | {
|
|
100
|
+
success: false;
|
|
101
|
+
data: {
|
|
102
|
+
status: number;
|
|
103
|
+
message: string;
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
type After<BeforeAfterContext> = (ctx: BeforeAfterContext, result: HandlerResult) => Promise<void>;
|
|
107
|
+
type ServerConfigWithBefore<BeforeAfterContext> = {
|
|
108
|
+
before: Before<BeforeAfterContext>;
|
|
109
|
+
after?: After<BeforeAfterContext>;
|
|
110
|
+
} | {
|
|
111
|
+
before?: undefined;
|
|
112
|
+
};
|
|
113
|
+
type ServerConfig<ContextFrom, BeforeAfterContext> = ServerConfigWithBefore<BeforeAfterContext> & {
|
|
114
|
+
router: Router<ContextFrom, unknown, any>;
|
|
115
|
+
getContext: GetContext<ContextFrom>;
|
|
116
|
+
rawRoutes?: Partial<Record<KaitoMethod, Array<{
|
|
117
|
+
path: string;
|
|
118
|
+
handler: (request: http$1.IncomingMessage, response: http$1.ServerResponse) => unknown;
|
|
119
|
+
}>>>;
|
|
120
|
+
onError(arg: {
|
|
121
|
+
error: Error;
|
|
122
|
+
req: KaitoRequest;
|
|
123
|
+
res: KaitoResponse;
|
|
124
|
+
}): Promise<KaitoError | {
|
|
125
|
+
status: number;
|
|
126
|
+
message: string;
|
|
127
|
+
}>;
|
|
128
|
+
};
|
|
129
|
+
declare function createFMWServer<Context, BeforeAfterContext = null>(config: ServerConfig<Context, BeforeAfterContext>): {
|
|
130
|
+
readonly server: http$1.Server<typeof http$1.IncomingMessage, typeof http$1.ServerResponse>;
|
|
131
|
+
readonly fmw: find_my_way.Instance<find_my_way.HTTPVersion.V1>;
|
|
132
|
+
};
|
|
133
|
+
declare function createServer<Context, BeforeAfterContext = null>(config: ServerConfig<Context, BeforeAfterContext>): http$1.Server<typeof http$1.IncomingMessage, typeof http$1.ServerResponse>;
|
|
134
|
+
|
|
135
|
+
type PrefixRoutesPathInner<R extends AnyRoute, Prefix extends `/${string}`> = R extends Route<infer ContextFrom, infer ContextTo, infer Result, infer Path, infer Method, infer Query, infer BodyOutput> ? Route<ContextFrom, ContextTo, Result, `${Prefix}${Path}`, Method, Query, BodyOutput> : never;
|
|
136
|
+
type PrefixRoutesPath<Prefix extends `/${string}`, R extends AnyRoute> = R extends R ? PrefixRoutesPathInner<R, Prefix> : never;
|
|
137
|
+
type RouterOptions<ContextFrom, ContextTo> = {
|
|
138
|
+
through: (context: ContextFrom) => Promise<ContextTo>;
|
|
139
|
+
};
|
|
140
|
+
declare class Router<ContextFrom, ContextTo, R extends AnyRoute> {
|
|
141
|
+
private readonly routerOptions;
|
|
142
|
+
readonly routes: Set<R>;
|
|
143
|
+
static create: <Context>() => Router<Context, Context, never>;
|
|
144
|
+
private static parseQuery;
|
|
145
|
+
private static handle;
|
|
146
|
+
constructor(routes: Iterable<R>, options: RouterOptions<ContextFrom, ContextTo>);
|
|
147
|
+
/**
|
|
148
|
+
* Adds a new route to the router
|
|
149
|
+
* @deprecated Use the method-specific methods instead
|
|
150
|
+
*/
|
|
151
|
+
add: <Result, Path extends string, Method extends KaitoMethod, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(method: Method, path: Path, route: (Method extends "GET" ? Omit<Route<ContextFrom, ContextTo, Result, Path, Method, Query, Body>, "body" | "path" | "method" | "through"> : Omit<Route<ContextFrom, ContextTo, Result, Path, Method, Query, Body>, "path" | "method" | "through">) | Route<ContextFrom, ContextTo, Result, Path, Method, Query, Body>["run"]) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, Method, Query, Body>>;
|
|
152
|
+
readonly merge: <PathPrefix extends `/${string}`, OtherRoutes extends AnyRoute>(pathPrefix: PathPrefix, other: Router<ContextFrom, unknown, OtherRoutes>) => Router<ContextFrom, ContextTo, Extract<R | PrefixRoutesPath<PathPrefix, OtherRoutes>, AnyRoute>>;
|
|
153
|
+
freeze: (server: ServerConfig<ContextFrom, any>) => find_my_way__default.Instance<find_my_way__default.HTTPVersion.V1>;
|
|
154
|
+
private readonly method;
|
|
155
|
+
get: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "GET", Query, Body>, "body" | "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "GET", Query, Body>>;
|
|
156
|
+
post: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "POST", Query, Body>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "POST", Query, Body>>;
|
|
157
|
+
put: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "PUT", Query, Body>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "PUT", Query, Body>>;
|
|
158
|
+
patch: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "PATCH", Query, Body>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "PATCH", Query, Body>>;
|
|
159
|
+
delete: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "DELETE", Query, Body>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "DELETE", Query, Body>>;
|
|
160
|
+
head: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "HEAD", Query, Body>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "HEAD", Query, Body>>;
|
|
161
|
+
options: <Result, Path extends string, Query extends AnyQueryDefinition = {}, Body extends Parsable = never>(path: Path, route: ((arg: RouteArgument<Path, ContextTo, { [Key in keyof Query]: InferParsable<Query[Key]>["output"]; }, InferParsable<Body>["output"]>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "OPTIONS", Query, Body>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, R | Route<ContextFrom, ContextTo, Result, Path, "OPTIONS", Query, Body>>;
|
|
162
|
+
through: <NextContext>(transform: (context: ContextTo) => Promise<NextContext>) => Router<ContextFrom, NextContext, R>;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
type ExtractRouteParams<T extends string> = string extends T ? Record<string, string> : T extends `${string}:${infer Param}/${infer Rest}` ? {
|
|
166
|
+
[k in Param | keyof ExtractRouteParams<Rest>]: string;
|
|
167
|
+
} : T extends `${string}:${infer Param}` ? {
|
|
168
|
+
[k in Param]: string;
|
|
169
|
+
} : {};
|
|
170
|
+
type KaitoMethod = HTTPMethod | '*';
|
|
171
|
+
type GetContext<Result> = (req: KaitoRequest, res: KaitoResponse) => Promise<Result>;
|
|
172
|
+
/**
|
|
173
|
+
* @deprecated use `createUtilities` instead
|
|
174
|
+
*/
|
|
175
|
+
declare function createGetContext<Context>(callback: GetContext<Context>): GetContext<Context>;
|
|
176
|
+
/**
|
|
177
|
+
* A helper function to create typed necessary functions
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```ts
|
|
181
|
+
* const {router, getContext} = createUtilities(async (req, res) => {
|
|
182
|
+
* // Return context here
|
|
183
|
+
* })
|
|
184
|
+
*
|
|
185
|
+
* const app = router().get('/', async () => "hello");
|
|
186
|
+
*
|
|
187
|
+
* const server = createServer({
|
|
188
|
+
* router: app,
|
|
189
|
+
* getContext,
|
|
190
|
+
* // ...
|
|
191
|
+
* });
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
declare function createUtilities<Context>(getContext: GetContext<Context>): {
|
|
195
|
+
getContext: GetContext<Context>;
|
|
196
|
+
router: () => Router<Context, Context, never>;
|
|
197
|
+
};
|
|
198
|
+
type InferContext<T> = T extends (req: KaitoRequest, res: KaitoResponse) => Promise<infer U> ? U : never;
|
|
199
|
+
declare function getLastEntryInMultiHeaderValue(headerValue: string | string[]): string;
|
|
200
|
+
interface Parsable<Output = any, Input = Output> {
|
|
201
|
+
_input?: Input;
|
|
202
|
+
parse: (value: unknown) => Output;
|
|
203
|
+
}
|
|
204
|
+
type InferParsable<T> = T extends Parsable<infer Output, infer Input> ? {
|
|
205
|
+
input: Input;
|
|
206
|
+
output: Output;
|
|
207
|
+
} : never;
|
|
208
|
+
type RemoveEndSlashes<T extends string> = T extends `${infer U}/` ? U : T;
|
|
209
|
+
type AddStartSlashes<T extends string> = T extends `/${infer U}` ? `/${U}` : `/${T}`;
|
|
210
|
+
type NormalizePath<T extends string> = AddStartSlashes<RemoveEndSlashes<T>>;
|
|
211
|
+
type Values<T> = T[keyof T];
|
|
212
|
+
type NoEmpty<T> = [keyof T] extends [never] ? never : T;
|
|
213
|
+
declare function getBody(req: KaitoRequest): Promise<unknown>;
|
|
214
|
+
|
|
215
|
+
type RouteArgument<Path extends string, Context, QueryOutput, BodyOutput> = {
|
|
216
|
+
ctx: Context;
|
|
217
|
+
body: BodyOutput;
|
|
218
|
+
query: QueryOutput;
|
|
219
|
+
params: ExtractRouteParams<Path>;
|
|
220
|
+
};
|
|
221
|
+
type AnyQueryDefinition = Record<string, Parsable>;
|
|
222
|
+
type RouteRunner<Result, Path extends string, Context, QueryOutput, BodyOutput> = (args: RouteArgument<Path, Context, QueryOutput, BodyOutput>) => Promise<Result>;
|
|
223
|
+
type Route<ContextFrom, ContextTo, Result, Path extends string, Method extends KaitoMethod, Query extends AnyQueryDefinition, Body extends Parsable> = {
|
|
224
|
+
through: (context: ContextFrom) => Promise<ContextTo>;
|
|
225
|
+
body?: Body;
|
|
226
|
+
query?: Query;
|
|
227
|
+
path: Path;
|
|
228
|
+
method: Method;
|
|
229
|
+
run(arg: RouteArgument<Path, ContextTo, {
|
|
230
|
+
[Key in keyof Query]: InferParsable<Query[Key]>['output'];
|
|
231
|
+
}, InferParsable<Body>['output']>): Promise<Result>;
|
|
232
|
+
};
|
|
233
|
+
type AnyRoute<FromContext = any, ToContext = any> = Route<FromContext, ToContext, any, any, any, AnyQueryDefinition, any>;
|
|
234
|
+
|
|
235
|
+
export { type APIResponse, type AddStartSlashes, type After, type AnyQueryDefinition, type AnyResponse, type AnyRoute, type Before, type ErroredAPIResponse, type ExtractRouteParams, type GetContext, type HandlerResult, type InferContext, type InferParsable, KaitoError, type KaitoMethod, KaitoRequest, KaitoResponse, type NoEmpty, type NormalizePath, type Parsable, type RemoveEndSlashes, type Route, type RouteArgument, type RouteRunner, Router, type RouterOptions, type ServerConfig, type ServerConfigWithBefore, type SuccessfulAPIResponse, type Values, WrappedError, createFMWServer, createGetContext, createServer, createUtilities, getBody, getLastEntryInMultiHeaderValue };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// src/error.ts
|
|
2
|
+
var WrappedError = class _WrappedError extends Error {
|
|
3
|
+
constructor(data) {
|
|
4
|
+
super("Something was thrown, but it was not an instance of Error, so a WrappedError was created.");
|
|
5
|
+
this.data = data;
|
|
6
|
+
}
|
|
7
|
+
static maybe(maybeError) {
|
|
8
|
+
if (maybeError instanceof Error) {
|
|
9
|
+
return maybeError;
|
|
10
|
+
}
|
|
11
|
+
return _WrappedError.from(maybeError);
|
|
12
|
+
}
|
|
13
|
+
static from(data) {
|
|
14
|
+
return new _WrappedError(data);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var KaitoError = class extends Error {
|
|
18
|
+
constructor(status, message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// src/req.ts
|
|
25
|
+
import { TLSSocket } from "node:tls";
|
|
26
|
+
|
|
27
|
+
// src/util.ts
|
|
28
|
+
import { parse as parseContentType } from "content-type";
|
|
29
|
+
import { Readable } from "node:stream";
|
|
30
|
+
import { json } from "node:stream/consumers";
|
|
31
|
+
import getRawBody from "raw-body";
|
|
32
|
+
|
|
33
|
+
// src/router.ts
|
|
34
|
+
import fmw from "find-my-way";
|
|
35
|
+
|
|
36
|
+
// src/res.ts
|
|
37
|
+
import { serialize } from "cookie";
|
|
38
|
+
var KaitoResponse = class {
|
|
39
|
+
constructor(raw) {
|
|
40
|
+
this.raw = raw;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Send a response
|
|
44
|
+
* @param key The key of the header
|
|
45
|
+
* @param value The value of the header
|
|
46
|
+
* @returns The response object
|
|
47
|
+
*/
|
|
48
|
+
header(key, value) {
|
|
49
|
+
this.raw.setHeader(key, value);
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Set the status code of the response
|
|
54
|
+
* @param code The status code
|
|
55
|
+
* @returns The response object
|
|
56
|
+
*/
|
|
57
|
+
status(code) {
|
|
58
|
+
this.raw.statusCode = code;
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Set a cookie
|
|
63
|
+
* @param name The name of the cookie
|
|
64
|
+
* @param value The value of the cookie
|
|
65
|
+
* @param options The options for the cookie
|
|
66
|
+
* @returns The response object
|
|
67
|
+
*/
|
|
68
|
+
cookie(name, value, options) {
|
|
69
|
+
this.raw.setHeader("Set-Cookie", serialize(name, value, options));
|
|
70
|
+
return this;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Send a JSON APIResponse body
|
|
74
|
+
* @param data The data to send
|
|
75
|
+
* @returns The response object
|
|
76
|
+
*/
|
|
77
|
+
json(data) {
|
|
78
|
+
const json2 = JSON.stringify(data);
|
|
79
|
+
this.raw.setHeader("Content-Type", "application/json");
|
|
80
|
+
this.raw.setHeader("Content-Length", Buffer.byteLength(json2));
|
|
81
|
+
this.raw.end(json2);
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// src/router.ts
|
|
87
|
+
var getSend = (res) => (status, response) => {
|
|
88
|
+
if (res.raw.headersSent) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
res.status(status).json(response);
|
|
92
|
+
};
|
|
93
|
+
var Router = class _Router {
|
|
94
|
+
routerOptions;
|
|
95
|
+
routes;
|
|
96
|
+
static create = () => new _Router([], {
|
|
97
|
+
through: async (context) => context
|
|
98
|
+
});
|
|
99
|
+
static parseQuery(schema, url) {
|
|
100
|
+
if (!schema) {
|
|
101
|
+
return {};
|
|
102
|
+
}
|
|
103
|
+
const result = {};
|
|
104
|
+
for (const [key, value] of url.searchParams.entries()) {
|
|
105
|
+
const parsable = schema[key];
|
|
106
|
+
if (!parsable) {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const parsed = parsable.parse(value);
|
|
110
|
+
result[key] = parsed;
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
static async handle(server, route, options) {
|
|
115
|
+
const send = getSend(options.res);
|
|
116
|
+
try {
|
|
117
|
+
const rootCtx = await server.getContext(options.req, options.res);
|
|
118
|
+
const ctx = await route.through(rootCtx);
|
|
119
|
+
const body = await route.body?.parse(await getBody(options.req)) ?? void 0;
|
|
120
|
+
const query = _Router.parseQuery(route.query, options.req.url);
|
|
121
|
+
const result = await route.run({
|
|
122
|
+
ctx,
|
|
123
|
+
body,
|
|
124
|
+
query,
|
|
125
|
+
params: options.params
|
|
126
|
+
});
|
|
127
|
+
if (options.res.raw.headersSent) {
|
|
128
|
+
return {
|
|
129
|
+
success: true,
|
|
130
|
+
data: result
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
send(200, {
|
|
134
|
+
success: true,
|
|
135
|
+
data: result,
|
|
136
|
+
message: "OK"
|
|
137
|
+
});
|
|
138
|
+
return {
|
|
139
|
+
success: true,
|
|
140
|
+
data: result
|
|
141
|
+
};
|
|
142
|
+
} catch (e) {
|
|
143
|
+
const error = WrappedError.maybe(e);
|
|
144
|
+
if (error instanceof KaitoError) {
|
|
145
|
+
send(error.status, {
|
|
146
|
+
success: false,
|
|
147
|
+
data: null,
|
|
148
|
+
message: error.message
|
|
149
|
+
});
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const { status, message } = await server.onError({ error, req: options.req, res: options.res }).catch(() => ({ status: 500, message: "Internal Server Error" }));
|
|
153
|
+
send(status, {
|
|
154
|
+
success: false,
|
|
155
|
+
data: null,
|
|
156
|
+
message
|
|
157
|
+
});
|
|
158
|
+
return {
|
|
159
|
+
success: false,
|
|
160
|
+
data: { status, message }
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
constructor(routes, options) {
|
|
165
|
+
this.routerOptions = options;
|
|
166
|
+
this.routes = new Set(routes);
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Adds a new route to the router
|
|
170
|
+
* @deprecated Use the method-specific methods instead
|
|
171
|
+
*/
|
|
172
|
+
add = (method, path, route) => {
|
|
173
|
+
const merged = {
|
|
174
|
+
...typeof route === "object" ? route : { run: route },
|
|
175
|
+
method,
|
|
176
|
+
path,
|
|
177
|
+
through: this.routerOptions.through
|
|
178
|
+
};
|
|
179
|
+
return new _Router([...this.routes, merged], this.routerOptions);
|
|
180
|
+
};
|
|
181
|
+
merge = (pathPrefix, other) => {
|
|
182
|
+
const newRoutes = [...other.routes].map((route) => ({
|
|
183
|
+
...route,
|
|
184
|
+
path: `${pathPrefix}${route.path}`
|
|
185
|
+
}));
|
|
186
|
+
return new _Router(
|
|
187
|
+
[...this.routes, ...newRoutes],
|
|
188
|
+
this.routerOptions
|
|
189
|
+
);
|
|
190
|
+
};
|
|
191
|
+
// Allow for any server context to be passed
|
|
192
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
193
|
+
freeze = (server) => {
|
|
194
|
+
const instance = fmw({
|
|
195
|
+
ignoreTrailingSlash: true,
|
|
196
|
+
async defaultRoute(req, serverResponse) {
|
|
197
|
+
const res = new KaitoResponse(serverResponse);
|
|
198
|
+
const message = `Cannot ${req.method} ${req.url ?? "/"}`;
|
|
199
|
+
getSend(res)(404, {
|
|
200
|
+
success: false,
|
|
201
|
+
data: null,
|
|
202
|
+
message
|
|
203
|
+
});
|
|
204
|
+
return {
|
|
205
|
+
success: false,
|
|
206
|
+
data: { status: 404, message }
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
for (const route of this.routes) {
|
|
211
|
+
const handler = async (incomingMessage, serverResponse, params) => {
|
|
212
|
+
const req = new KaitoRequest(incomingMessage);
|
|
213
|
+
const res = new KaitoResponse(serverResponse);
|
|
214
|
+
return _Router.handle(server, route, {
|
|
215
|
+
params,
|
|
216
|
+
req,
|
|
217
|
+
res
|
|
218
|
+
});
|
|
219
|
+
};
|
|
220
|
+
if (route.method === "*") {
|
|
221
|
+
instance.all(route.path, handler);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
instance.on(route.method, route.path, handler);
|
|
225
|
+
}
|
|
226
|
+
return instance;
|
|
227
|
+
};
|
|
228
|
+
method = (method) => (path, route) => {
|
|
229
|
+
return this.add(method, path, route);
|
|
230
|
+
};
|
|
231
|
+
get = this.method("GET");
|
|
232
|
+
post = this.method("POST");
|
|
233
|
+
put = this.method("PUT");
|
|
234
|
+
patch = this.method("PATCH");
|
|
235
|
+
delete = this.method("DELETE");
|
|
236
|
+
head = this.method("HEAD");
|
|
237
|
+
options = this.method("OPTIONS");
|
|
238
|
+
through = (transform) => new _Router(this.routes, {
|
|
239
|
+
through: async (context) => {
|
|
240
|
+
const fromCurrentRouter = await this.routerOptions.through(context);
|
|
241
|
+
return transform(fromCurrentRouter);
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
// src/util.ts
|
|
247
|
+
function createGetContext(callback) {
|
|
248
|
+
return callback;
|
|
249
|
+
}
|
|
250
|
+
function createUtilities(getContext) {
|
|
251
|
+
return {
|
|
252
|
+
getContext,
|
|
253
|
+
router: () => Router.create()
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function getLastEntryInMultiHeaderValue(headerValue) {
|
|
257
|
+
const normalized = Array.isArray(headerValue) ? headerValue.join(",") : headerValue;
|
|
258
|
+
const lastIndex = normalized.lastIndexOf(",");
|
|
259
|
+
return lastIndex === -1 ? normalized.trim() : normalized.slice(lastIndex + 1).trim();
|
|
260
|
+
}
|
|
261
|
+
async function getBody(req) {
|
|
262
|
+
if (!req.headers["content-type"]) {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
const buffer = await getRawBody(req.raw);
|
|
266
|
+
const { type } = parseContentType(req.headers["content-type"]);
|
|
267
|
+
switch (type) {
|
|
268
|
+
case "application/json": {
|
|
269
|
+
return json(Readable.from(buffer));
|
|
270
|
+
}
|
|
271
|
+
default: {
|
|
272
|
+
if (process.env.NODE_ENV === "development") {
|
|
273
|
+
console.warn("[kaito] Unsupported content type:", type);
|
|
274
|
+
console.warn("[kaito] This message is only shown in development mode.");
|
|
275
|
+
}
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// src/req.ts
|
|
282
|
+
var KaitoRequest = class {
|
|
283
|
+
constructor(raw) {
|
|
284
|
+
this.raw = raw;
|
|
285
|
+
}
|
|
286
|
+
_url = null;
|
|
287
|
+
/**
|
|
288
|
+
* The full URL of the request, including the protocol, hostname, and path.
|
|
289
|
+
* Note: does not include the query string or hash
|
|
290
|
+
*/
|
|
291
|
+
get fullURL() {
|
|
292
|
+
return `${this.protocol}://${this.hostname}${this.raw.url ?? ""}`;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* A new URL instance for the full URL of the request.
|
|
296
|
+
*/
|
|
297
|
+
get url() {
|
|
298
|
+
if (this._url) {
|
|
299
|
+
return this._url;
|
|
300
|
+
}
|
|
301
|
+
this._url = new URL(this.fullURL);
|
|
302
|
+
return this._url;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The HTTP method of the request.
|
|
306
|
+
*/
|
|
307
|
+
get method() {
|
|
308
|
+
if (!this.raw.method) {
|
|
309
|
+
throw new Error("Request method is not defined, somehow...");
|
|
310
|
+
}
|
|
311
|
+
return this.raw.method;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* The protocol of the request, either `http` or `https`.
|
|
315
|
+
*/
|
|
316
|
+
get protocol() {
|
|
317
|
+
if (this.raw.socket instanceof TLSSocket) {
|
|
318
|
+
return this.raw.socket.encrypted ? "https" : "http";
|
|
319
|
+
}
|
|
320
|
+
return "http";
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* The request headers
|
|
324
|
+
*/
|
|
325
|
+
get headers() {
|
|
326
|
+
return this.raw.headers;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* The hostname of the request.
|
|
330
|
+
*/
|
|
331
|
+
get hostname() {
|
|
332
|
+
return this.raw.headers.host ?? getLastEntryInMultiHeaderValue(this.raw.headers[":authority"] ?? []);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// src/server.ts
|
|
337
|
+
import * as http from "node:http";
|
|
338
|
+
function createFMWServer(config) {
|
|
339
|
+
const router = config.router.freeze(config);
|
|
340
|
+
const rawRoutes = config.rawRoutes ?? {};
|
|
341
|
+
for (const method in rawRoutes) {
|
|
342
|
+
if (!Object.prototype.hasOwnProperty.call(rawRoutes, method)) {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const routes = rawRoutes[method];
|
|
346
|
+
if (!routes || routes.length === 0) {
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
for (const route of routes) {
|
|
350
|
+
if (method === "*") {
|
|
351
|
+
router.all(route.path, route.handler);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
router[method.toLowerCase()](route.path, route.handler);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const server = http.createServer(async (req, res) => {
|
|
358
|
+
let before;
|
|
359
|
+
if (config.before) {
|
|
360
|
+
before = await config.before(req, res);
|
|
361
|
+
} else {
|
|
362
|
+
before = void 0;
|
|
363
|
+
}
|
|
364
|
+
if (res.headersSent) {
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const result = await router.lookup(req, res);
|
|
368
|
+
if ("after" in config && config.after) {
|
|
369
|
+
await config.after(before, result);
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
return { server, fmw: router };
|
|
373
|
+
}
|
|
374
|
+
function createServer2(config) {
|
|
375
|
+
return createFMWServer(config).server;
|
|
376
|
+
}
|
|
377
|
+
export {
|
|
378
|
+
KaitoError,
|
|
379
|
+
KaitoRequest,
|
|
380
|
+
KaitoResponse,
|
|
381
|
+
Router,
|
|
382
|
+
WrappedError,
|
|
383
|
+
createFMWServer,
|
|
384
|
+
createGetContext,
|
|
385
|
+
createServer2 as createServer,
|
|
386
|
+
createUtilities,
|
|
387
|
+
getBody,
|
|
388
|
+
getLastEntryInMultiHeaderValue
|
|
389
|
+
};
|
package/package.json
CHANGED
|
@@ -1,35 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaito-http/core",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.4",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"author": "Alistair Smith <hi@alistair.sh>",
|
|
4
6
|
"description": "Functional HTTP Framework for TypeScript",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsup"
|
|
9
|
+
},
|
|
5
10
|
"exports": {
|
|
6
|
-
".": "./
|
|
7
|
-
"
|
|
11
|
+
"./package.json": "./package.json",
|
|
12
|
+
".": "./dist/index.js"
|
|
8
13
|
},
|
|
14
|
+
"homepage": "https://github.com/kaito-http/kaito",
|
|
9
15
|
"repository": "https://github.com/kaito-http/kaito",
|
|
10
|
-
"
|
|
16
|
+
"keywords": [
|
|
17
|
+
"typescript",
|
|
18
|
+
"http",
|
|
19
|
+
"framework"
|
|
20
|
+
],
|
|
11
21
|
"license": "MIT",
|
|
12
|
-
"type": "module",
|
|
13
22
|
"devDependencies": {
|
|
14
|
-
"@types/content-type": "^1.1.
|
|
15
|
-
"@types/cookie": "^0.
|
|
16
|
-
"@types/node": "^
|
|
23
|
+
"@types/content-type": "^1.1.8",
|
|
24
|
+
"@types/cookie": "^0.6.0",
|
|
25
|
+
"@types/node": "^22.7.4",
|
|
17
26
|
"typescript": "^5.6.2"
|
|
18
27
|
},
|
|
19
28
|
"files": [
|
|
20
29
|
"package.json",
|
|
21
|
-
"
|
|
30
|
+
"README.md",
|
|
22
31
|
"dist"
|
|
23
32
|
],
|
|
24
33
|
"bugs": {
|
|
25
34
|
"url": "https://github.com/kaito-http/kaito/issues"
|
|
26
35
|
},
|
|
27
|
-
"homepage": "https://github.com/kaito-http/kaito",
|
|
28
|
-
"keywords": [
|
|
29
|
-
"typescript",
|
|
30
|
-
"http",
|
|
31
|
-
"framework"
|
|
32
|
-
],
|
|
33
36
|
"dependencies": {
|
|
34
37
|
"content-type": "^1.0.5",
|
|
35
38
|
"cookie": "^0.6.0",
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
export declare class WrappedError<T> extends Error {
|
|
2
|
-
readonly data: T;
|
|
3
|
-
static maybe<T>(maybeError: T): (T & Error) | WrappedError<T>;
|
|
4
|
-
static from<T>(data: T): WrappedError<T>;
|
|
5
|
-
private constructor();
|
|
6
|
-
}
|
|
7
|
-
export declare class KaitoError extends Error {
|
|
8
|
-
readonly status: number;
|
|
9
|
-
constructor(status: number, message: string);
|
|
10
|
-
}
|