@kaito-http/core 2.9.5 → 3.0.0-beta.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/README.md CHANGED
@@ -1,12 +1,9 @@
1
1
  # `kaito-http`
2
2
 
3
- [![Vercel](https://github.com/kaito-http/kaito/raw/main/static/powered-by-vercel.svg)](https://vercel.com?utm_source=kaito-http&utm_campaign=oss)
4
-
5
3
  #### An HTTP Framework for TypeScript
6
4
 
7
5
  View the [documentation here](https://kaito.cloud)
8
6
 
9
7
  #### Credits
10
8
 
11
- - [Vercel](https://vercel.com?utm_source=kaito-http&utm_campaign=oss), for sponsoring the project and hosting the documentation
12
- - [Alistair Smith](https://twitter.com/aabbccsmith)
9
+ - [Alistair Smith](https://twitter.com/alistaiir)
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,41 +1,42 @@
1
1
  {
2
2
  "name": "@kaito-http/core",
3
- "version": "2.9.5",
3
+ "version": "3.0.0-beta.3",
4
+ "type": "module",
5
+ "author": "Alistair Smith <hi@alistair.sh>",
4
6
  "description": "Functional HTTP Framework for TypeScript",
7
+ "scripts": {
8
+ "build": "tsup"
9
+ },
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ ".": "./dist/index.js"
13
+ },
14
+ "homepage": "https://github.com/kaito-http/kaito",
5
15
  "repository": "https://github.com/kaito-http/kaito",
6
- "author": "Alistair Smith <hi@alistair.sh>",
16
+ "keywords": [
17
+ "typescript",
18
+ "http",
19
+ "framework"
20
+ ],
7
21
  "license": "MIT",
8
- "main": "dist/kaito-http-core.cjs.js",
9
- "module": "dist/kaito-http-core.esm.js",
10
- "types": "dist/kaito-http-core.cjs.d.ts",
11
22
  "devDependencies": {
12
- "@types/content-type": "^1.1.5",
13
- "@types/cookie": "^0.5.1",
14
- "@types/node": "^18.11.9",
15
- "typescript": "4.9",
16
- "zod": "^3.19.1"
23
+ "@types/content-type": "^1.1.8",
24
+ "@types/cookie": "^0.6.0",
25
+ "@types/node": "^22.7.4",
26
+ "typescript": "^5.6.2"
17
27
  },
18
28
  "files": [
19
29
  "package.json",
20
- "readme.md",
30
+ "README.md",
21
31
  "dist"
22
32
  ],
23
33
  "bugs": {
24
34
  "url": "https://github.com/kaito-http/kaito/issues"
25
35
  },
26
- "homepage": "https://github.com/kaito-http/kaito",
27
- "peerDependencies": {
28
- "zod": "*"
29
- },
30
- "keywords": [
31
- "typescript",
32
- "http",
33
- "framework"
34
- ],
35
36
  "dependencies": {
36
- "content-type": "^1.0.4",
37
- "cookie": "^0.5.0",
38
- "find-my-way": "^7.3.1",
39
- "raw-body": "^2.5.1"
37
+ "content-type": "^1.0.5",
38
+ "cookie": "^0.6.0",
39
+ "find-my-way": "^9.1.0",
40
+ "raw-body": "^3.0.0"
40
41
  }
41
42
  }
@@ -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
- }
@@ -1,8 +0,0 @@
1
- export type { HTTPMethod } from 'find-my-way';
2
- export * from './error';
3
- export * from './req';
4
- export * from './res';
5
- export * from './route';
6
- export * from './router';
7
- export * from './server';
8
- export * from './util';
@@ -1,33 +0,0 @@
1
- /// <reference types="node" />
2
- import type { HTTPMethod } from 'find-my-way';
3
- import type { IncomingMessage } from 'node:http';
4
- export declare class KaitoRequest {
5
- readonly raw: IncomingMessage;
6
- private _url;
7
- constructor(raw: IncomingMessage);
8
- /**
9
- * The full URL of the request, including the protocol, hostname, and path.
10
- * Note: does not include the query string or hash
11
- */
12
- get fullURL(): string;
13
- /**
14
- * A new URL instance for the full URL of the request.
15
- */
16
- get url(): URL;
17
- /**
18
- * The HTTP method of the request.
19
- */
20
- get method(): HTTPMethod;
21
- /**
22
- * The protocol of the request, either `http` or `https`.
23
- */
24
- get protocol(): 'http' | 'https';
25
- /**
26
- * The request headers
27
- */
28
- get headers(): import("http").IncomingHttpHeaders;
29
- /**
30
- * The hostname of the request.
31
- */
32
- get hostname(): string;
33
- }
@@ -1,46 +0,0 @@
1
- /// <reference types="node" />
2
- import type { ServerResponse } from 'node:http';
3
- import type { CookieSerializeOptions } from 'cookie';
4
- export type ErroredAPIResponse = {
5
- success: false;
6
- data: null;
7
- message: string;
8
- };
9
- export type SuccessfulAPIResponse<T> = {
10
- success: true;
11
- data: T;
12
- message: 'OK';
13
- };
14
- export type APIResponse<T> = ErroredAPIResponse | SuccessfulAPIResponse<T>;
15
- export type AnyResponse = APIResponse<unknown>;
16
- export declare class KaitoResponse<T = unknown> {
17
- readonly raw: ServerResponse;
18
- constructor(raw: ServerResponse);
19
- /**
20
- * Send a response
21
- * @param key The key of the header
22
- * @param value The value of the header
23
- * @returns The response object
24
- */
25
- header(key: string, value: string | readonly string[]): this;
26
- /**
27
- * Set the status code of the response
28
- * @param code The status code
29
- * @returns The response object
30
- */
31
- status(code: number): this;
32
- /**
33
- * Set a cookie
34
- * @param name The name of the cookie
35
- * @param value The value of the cookie
36
- * @param options The options for the cookie
37
- * @returns The response object
38
- */
39
- cookie(name: string, value: string, options: CookieSerializeOptions): this;
40
- /**
41
- * Send a JSON APIResponse body
42
- * @param data The data to send
43
- * @returns The response object
44
- */
45
- json(data: APIResponse<T>): this;
46
- }
@@ -1,18 +0,0 @@
1
- import type { z } from 'zod';
2
- import type { ExtractRouteParams, KaitoMethod } from './util';
3
- export type RouteArgument<Path extends string, Context, QueryOutput, BodyOutput> = {
4
- ctx: Context;
5
- body: BodyOutput;
6
- query: QueryOutput;
7
- params: ExtractRouteParams<Path>;
8
- };
9
- export type AnyQueryDefinition = Record<string, z.ZodTypeAny>;
10
- export type Route<ContextFrom, ContextTo, Result, Path extends string, Method extends KaitoMethod, Query extends AnyQueryDefinition, BodyOutput, BodyDef extends z.ZodTypeDef, BodyInput> = {
11
- through: (context: ContextFrom) => Promise<ContextTo>;
12
- body?: z.ZodType<BodyOutput, BodyDef, BodyInput>;
13
- query?: Query;
14
- path: Path;
15
- method: Method;
16
- run(args: RouteArgument<Path, ContextTo, z.infer<z.ZodObject<Query>>, BodyOutput>): Promise<Result>;
17
- };
18
- export type AnyRoute<FromContext = any, ToContext = any> = Route<FromContext, ToContext, any, any, any, AnyQueryDefinition, any, any, any>;
@@ -1,41 +0,0 @@
1
- import fmw from 'find-my-way';
2
- import { z } from 'zod';
3
- import type { AnyQueryDefinition, AnyRoute, Route } from './route';
4
- import type { ServerConfig } from './server';
5
- import type { KaitoMethod } from './util';
6
- type Routes = readonly AnyRoute[];
7
- type RemapRoutePrefix<R extends AnyRoute, Prefix extends `/${string}`> = R extends Route<infer ContextFrom, infer ContextTo, infer Result, infer Path, infer Method, infer Query, infer BodyOutput, infer BodyDef, infer BodyInput> ? Route<ContextFrom, ContextTo, Result, `${Prefix}${Path}`, Method, Query, BodyOutput, BodyDef, BodyInput> : never;
8
- type PrefixRoutesPath<Prefix extends `/${string}`, R extends Routes> = R extends [infer First, ...infer Rest] ? [
9
- RemapRoutePrefix<Extract<First, AnyRoute>, Prefix>,
10
- ...PrefixRoutesPath<Prefix, Extract<Rest, readonly AnyRoute[]>>
11
- ] : [];
12
- export type RouterOptions<ContextFrom, ContextTo> = {
13
- through: (context: ContextFrom) => Promise<ContextTo>;
14
- };
15
- export declare class Router<ContextFrom, ContextTo, R extends Routes> {
16
- private readonly routerOptions;
17
- readonly routes: R;
18
- static create: <Context>() => Router<Context, Context, []>;
19
- private static handle;
20
- constructor(routes: R, options: RouterOptions<ContextFrom, ContextTo>);
21
- /**
22
- * Adds a new route to the router
23
- * @param method The HTTP method to add a route for
24
- * @param path The path to add a route for
25
- * @param route The route specification to add to this router
26
- * @returns A new router with this route added
27
- */
28
- add: <Result, Path extends string, Method extends KaitoMethod, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(method: Method, path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | (Method extends "GET" ? Omit<Route<ContextFrom, ContextTo, Result, Path, Method, Query, BodyOutput, BodyDef, BodyInput>, "path" | "body" | "method" | "through"> : Omit<Route<ContextFrom, ContextTo, Result, Path, Method, Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">)) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, Method, Query, BodyOutput, BodyDef, BodyInput>]>;
29
- readonly merge: <PathPrefix extends `/${string}`, OtherRoutes extends Routes>(pathPrefix: PathPrefix, other: Router<ContextFrom, unknown, OtherRoutes>) => Router<ContextFrom, ContextTo, [...R, ...PrefixRoutesPath<PathPrefix, OtherRoutes>]>;
30
- freeze: (server: ServerConfig<ContextFrom, any>) => fmw.Instance<fmw.HTTPVersion.V1>;
31
- private readonly method;
32
- get: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "GET", Query, BodyOutput, BodyDef, BodyInput>, "path" | "body" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "GET", Query, BodyOutput, BodyDef, BodyInput>]>;
33
- post: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "POST", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "POST", Query, BodyOutput, BodyDef, BodyInput>]>;
34
- put: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "PUT", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "PUT", Query, BodyOutput, BodyDef, BodyInput>]>;
35
- patch: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "PATCH", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "PATCH", Query, BodyOutput, BodyDef, BodyInput>]>;
36
- delete: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "DELETE", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "DELETE", Query, BodyOutput, BodyDef, BodyInput>]>;
37
- head: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "HEAD", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "HEAD", Query, BodyOutput, BodyDef, BodyInput>]>;
38
- options: <Result, Path extends string, Query extends AnyQueryDefinition = {}, BodyOutput = never, BodyDef extends z.ZodTypeDef = z.ZodTypeDef, BodyInput = BodyOutput>(path: Path, route: ((args: import("./route").RouteArgument<Path, ContextTo, z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }> extends infer T extends object ? { [k in keyof T]: z.objectUtil.addQuestionMarks<{ [k_1 in keyof Query]: Query[k_1]["_output"]; }>[k]; } : never, BodyOutput>) => Promise<Result>) | Omit<Route<ContextFrom, ContextTo, Result, Path, "OPTIONS", Query, BodyOutput, BodyDef, BodyInput>, "path" | "method" | "through">) => Router<ContextFrom, ContextTo, [...R, Route<ContextFrom, ContextTo, Result, Path, "OPTIONS", Query, BodyOutput, BodyDef, BodyInput>]>;
39
- through: <NextContext>(transform: (context: ContextTo) => Promise<NextContext>) => Router<ContextFrom, NextContext, R>;
40
- }
41
- export {};
@@ -1,46 +0,0 @@
1
- /// <reference types="node" />
2
- import * as http from 'node:http';
3
- import type { KaitoError } from './error';
4
- import type { KaitoRequest } from './req';
5
- import type { KaitoResponse } from './res';
6
- import type { Router } from './router';
7
- import type { GetContext, KaitoMethod } from './util';
8
- export type Before<BeforeAfterContext> = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<BeforeAfterContext>;
9
- export type HandlerResult = {
10
- success: true;
11
- data: unknown;
12
- } | {
13
- success: false;
14
- data: {
15
- status: number;
16
- message: string;
17
- };
18
- };
19
- export type After<BeforeAfterContext> = (ctx: BeforeAfterContext, result: HandlerResult) => Promise<void>;
20
- export type ServerConfigWithBefore<BeforeAfterContext> = {
21
- before: Before<BeforeAfterContext>;
22
- after?: After<BeforeAfterContext>;
23
- } | {
24
- before?: undefined;
25
- };
26
- export type ServerConfig<ContextFrom, BeforeAfterContext> = ServerConfigWithBefore<BeforeAfterContext> & {
27
- router: Router<ContextFrom, unknown, any>;
28
- getContext: GetContext<ContextFrom>;
29
- rawRoutes?: Partial<Record<KaitoMethod, Array<{
30
- path: string;
31
- handler: (request: http.IncomingMessage, response: http.ServerResponse) => unknown;
32
- }>>>;
33
- onError(arg: {
34
- error: Error;
35
- req: KaitoRequest;
36
- res: KaitoResponse;
37
- }): Promise<KaitoError | {
38
- status: number;
39
- message: string;
40
- }>;
41
- };
42
- export declare function createFMWServer<Context, BeforeAfterContext = null>(config: ServerConfig<Context, BeforeAfterContext>): {
43
- readonly server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
44
- readonly fmw: import("find-my-way").Instance<import("find-my-way").HTTPVersion.V1>;
45
- };
46
- export declare function createServer<Context, BeforeAfterContext = null>(config: ServerConfig<Context, BeforeAfterContext>): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;