@kaito-http/core 3.0.0-beta.3 → 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.
Files changed (2) hide show
  1. package/dist/index.d.ts +235 -0
  2. package/package.json +1 -1
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaito-http/core",
3
- "version": "3.0.0-beta.3",
3
+ "version": "3.0.0-beta.4",
4
4
  "type": "module",
5
5
  "author": "Alistair Smith <hi@alistair.sh>",
6
6
  "description": "Functional HTTP Framework for TypeScript",