@kaito-http/core 1.3.2 → 2.0.0

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,12 @@
1
- # `kaito-http`
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
- #### An HTTP Framework for TypeScript
6
-
7
- View the [documentation here](https://kaito.cloud)
8
-
9
- #### Credits
10
-
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)
1
+ # `kaito-http`
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
+ #### An HTTP Framework for TypeScript
6
+
7
+ View the [documentation here](https://kaito.cloud)
8
+
9
+ #### Credits
10
+
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)
@@ -0,0 +1 @@
1
+ export * from './server';
@@ -0,0 +1,99 @@
1
+ /// <reference types="node" />
2
+ import { FastifyReply, FastifyRequest } from 'fastify';
3
+ import { z, ZodTypeAny } from 'zod';
4
+ export declare enum Method {
5
+ GET = "GET",
6
+ POST = "POST",
7
+ PATCH = "PATCH",
8
+ DELETE = "DELETE"
9
+ }
10
+ export declare type GetContext<T> = (req: FastifyRequest, res: FastifyReply) => Promise<T>;
11
+ declare type Never = [never];
12
+ export declare function createGetContext<T>(getContext: GetContext<T>): GetContext<T>;
13
+ export declare type InferContext<T> = T extends GetContext<infer Value> ? Value : never;
14
+ export declare type ContextWithInput<Ctx, Input> = {
15
+ ctx: Ctx;
16
+ input: Input;
17
+ };
18
+ declare type Values<T> = T[keyof T];
19
+ declare type Proc<Ctx, Result, Input extends z.ZodTypeAny | Never = Never> = Readonly<{
20
+ input?: Input;
21
+ run(arg: ContextWithInput<Ctx, Input extends ZodTypeAny ? z.infer<Input> : undefined>): Promise<Result>;
22
+ }>;
23
+ declare type ProcsInit<Ctx> = {
24
+ [Key in string]: Proc<Ctx, unknown, z.ZodTypeAny> & {
25
+ method: Method;
26
+ name: Key;
27
+ };
28
+ };
29
+ declare type AnyRouter<Ctx> = Router<Ctx, ProcsInit<Ctx>>;
30
+ export declare class Router<Ctx, Procs extends ProcsInit<Ctx>> {
31
+ private readonly procs;
32
+ constructor(procs: Procs);
33
+ getProcs(): Procs;
34
+ private readonly create;
35
+ readonly merge: <NewCtx>(router: AnyRouter<NewCtx>) => Router<NewCtx & Ctx, Procs & ProcsInit<NewCtx>>;
36
+ readonly get: <Name extends string, Result, Input extends z.ZodTypeAny>(name: Name, proc: Readonly<{
37
+ input?: Input | undefined;
38
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
39
+ }>) => Router<Ctx, Procs & Record<Name, Readonly<{
40
+ input?: Input | undefined;
41
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
42
+ }> & {
43
+ method: Method.GET;
44
+ name: Name;
45
+ }>>;
46
+ readonly post: <Name extends string, Result, Input extends z.ZodTypeAny>(name: Name, proc: Readonly<{
47
+ input?: Input | undefined;
48
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
49
+ }>) => Router<Ctx, Procs & Record<Name, Readonly<{
50
+ input?: Input | undefined;
51
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
52
+ }> & {
53
+ method: Method.POST;
54
+ name: Name;
55
+ }>>;
56
+ readonly patch: <Name extends string, Result, Input extends z.ZodTypeAny>(name: Name, proc: Readonly<{
57
+ input?: Input | undefined;
58
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
59
+ }>) => Router<Ctx, Procs & Record<Name, Readonly<{
60
+ input?: Input | undefined;
61
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
62
+ }> & {
63
+ method: Method.PATCH;
64
+ name: Name;
65
+ }>>;
66
+ readonly delete: <Name extends string, Result, Input extends z.ZodTypeAny>(name: Name, proc: Readonly<{
67
+ input?: Input | undefined;
68
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
69
+ }>) => Router<Ctx, Procs & Record<Name, Readonly<{
70
+ input?: Input | undefined;
71
+ run(arg: ContextWithInput<Ctx, Input extends z.ZodTypeAny ? z.TypeOf<Input> : undefined>): Promise<Result>;
72
+ }> & {
73
+ method: Method.DELETE;
74
+ name: Name;
75
+ }>>;
76
+ }
77
+ export declare class KaitoError extends Error {
78
+ readonly code: number;
79
+ readonly cause?: Error | undefined;
80
+ constructor(code: number, message: string, cause?: Error | undefined);
81
+ }
82
+ export declare function createRouter<Ctx>(): Router<Ctx, {}>;
83
+ export declare type InferApiResponseType<R extends AnyRouter<unknown>, M extends Method, Path extends Extract<Values<ReturnType<R['getProcs']>>, {
84
+ method: M;
85
+ }>['name']> = ReturnType<ReturnType<R['getProcs']>[Path]['run']> extends Promise<infer V> ? V : never;
86
+ export declare function createServer<Ctx, R extends Router<Ctx, ProcsInit<Ctx>>>(config: {
87
+ getContext: GetContext<Ctx>;
88
+ router: R;
89
+ onError(error: {
90
+ error: Error;
91
+ req: FastifyRequest;
92
+ res: FastifyReply;
93
+ }): Promise<{
94
+ code: number;
95
+ message: string;
96
+ }>;
97
+ log?: (message: string) => unknown | false;
98
+ }): import("fastify").FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance> & PromiseLike<import("fastify").FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance>>;
99
+ export {};
@@ -0,0 +1 @@
1
+ export * from "./declarations/src/index";
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var fastify = require('fastify');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
8
+
9
+ var fastify__default = /*#__PURE__*/_interopDefault(fastify);
10
+
11
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
12
+ try {
13
+ var info = gen[key](arg);
14
+ var value = info.value;
15
+ } catch (error) {
16
+ reject(error);
17
+ return;
18
+ }
19
+
20
+ if (info.done) {
21
+ resolve(value);
22
+ } else {
23
+ Promise.resolve(value).then(_next, _throw);
24
+ }
25
+ }
26
+
27
+ function _asyncToGenerator(fn) {
28
+ return function () {
29
+ var self = this,
30
+ args = arguments;
31
+ return new Promise(function (resolve, reject) {
32
+ var gen = fn.apply(self, args);
33
+
34
+ function _next(value) {
35
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
36
+ }
37
+
38
+ function _throw(err) {
39
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
40
+ }
41
+
42
+ _next(undefined);
43
+ });
44
+ };
45
+ }
46
+
47
+ function _defineProperty(obj, key, value) {
48
+ if (key in obj) {
49
+ Object.defineProperty(obj, key, {
50
+ value: value,
51
+ enumerable: true,
52
+ configurable: true,
53
+ writable: true
54
+ });
55
+ } else {
56
+ obj[key] = value;
57
+ }
58
+
59
+ return obj;
60
+ }
61
+
62
+ function ownKeys(object, enumerableOnly) {
63
+ var keys = Object.keys(object);
64
+
65
+ if (Object.getOwnPropertySymbols) {
66
+ var symbols = Object.getOwnPropertySymbols(object);
67
+
68
+ if (enumerableOnly) {
69
+ symbols = symbols.filter(function (sym) {
70
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
71
+ });
72
+ }
73
+
74
+ keys.push.apply(keys, symbols);
75
+ }
76
+
77
+ return keys;
78
+ }
79
+
80
+ function _objectSpread2(target) {
81
+ for (var i = 1; i < arguments.length; i++) {
82
+ var source = arguments[i] != null ? arguments[i] : {};
83
+
84
+ if (i % 2) {
85
+ ownKeys(Object(source), true).forEach(function (key) {
86
+ _defineProperty(target, key, source[key]);
87
+ });
88
+ } else if (Object.getOwnPropertyDescriptors) {
89
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
90
+ } else {
91
+ ownKeys(Object(source)).forEach(function (key) {
92
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
93
+ });
94
+ }
95
+ }
96
+
97
+ return target;
98
+ }
99
+
100
+ exports.Method = void 0;
101
+
102
+ (function (Method) {
103
+ Method["GET"] = "GET";
104
+ Method["POST"] = "POST";
105
+ Method["PATCH"] = "PATCH";
106
+ Method["DELETE"] = "DELETE";
107
+ })(exports.Method || (exports.Method = {}));
108
+
109
+ function createGetContext(getContext) {
110
+ return getContext;
111
+ }
112
+ class Router {
113
+ constructor(procs) {
114
+ _defineProperty(this, "create", method => (name, proc) => {
115
+ return new Router(_objectSpread2(_objectSpread2({}, this.procs), {}, {
116
+ [name]: _objectSpread2(_objectSpread2({}, proc), {}, {
117
+ method,
118
+ name
119
+ })
120
+ }));
121
+ });
122
+
123
+ _defineProperty(this, "merge", router => new Router(_objectSpread2(_objectSpread2({}, this.procs), router.getProcs())));
124
+
125
+ _defineProperty(this, "get", this.create(exports.Method.GET));
126
+
127
+ _defineProperty(this, "post", this.create(exports.Method.POST));
128
+
129
+ _defineProperty(this, "patch", this.create(exports.Method.PATCH));
130
+
131
+ _defineProperty(this, "delete", this.create(exports.Method.DELETE));
132
+
133
+ this.procs = procs;
134
+ }
135
+
136
+ getProcs() {
137
+ return this.procs;
138
+ }
139
+
140
+ }
141
+ class KaitoError extends Error {
142
+ constructor(code, message, cause) {
143
+ super(message);
144
+ this.code = code;
145
+ this.cause = cause;
146
+ }
147
+
148
+ }
149
+ function createRouter() {
150
+ return new Router({});
151
+ }
152
+ function createServer(config) {
153
+ var tree = config.router.getProcs();
154
+ var app = fastify__default["default"]();
155
+ app.setErrorHandler( /*#__PURE__*/function () {
156
+ var _ref = _asyncToGenerator(function* (error, req, res) {
157
+ if (error instanceof KaitoError) {
158
+ yield res.status(error.code).send({
159
+ success: false,
160
+ data: null,
161
+ message: error.message
162
+ });
163
+ return;
164
+ }
165
+
166
+ var {
167
+ code,
168
+ message
169
+ } = yield config.onError({
170
+ error,
171
+ req,
172
+ res
173
+ }).catch(() => ({
174
+ code: 500,
175
+ message: 'Something went wrong'
176
+ }));
177
+ yield res.status(code).send({
178
+ success: false,
179
+ data: null,
180
+ message
181
+ });
182
+ });
183
+
184
+ return function (_x, _x2, _x3) {
185
+ return _ref.apply(this, arguments);
186
+ };
187
+ }());
188
+ app.all('*', /*#__PURE__*/function () {
189
+ var _ref2 = _asyncToGenerator(function* (req, res) {
190
+ var _handler$input$parse, _handler$input;
191
+
192
+ var logMessage = "".concat(req.hostname, " ").concat(req.method, " ").concat(req.routerPath);
193
+
194
+ if (config.log === undefined) {
195
+ console.log(logMessage);
196
+ } else if (config.log) {
197
+ config.log(logMessage);
198
+ }
199
+
200
+ var url = new URL("".concat(req.protocol, "://").concat(req.hostname).concat(req.url));
201
+ var handler = tree[url.pathname];
202
+
203
+ if (!handler) {
204
+ throw new KaitoError(404, "Cannot ".concat(req.method, " this route."));
205
+ }
206
+
207
+ var context = yield config.getContext(req, res); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
208
+
209
+ var input = (_handler$input$parse = (_handler$input = handler.input) === null || _handler$input === void 0 ? void 0 : _handler$input.parse(req.method === 'GET' ? req.query : req.body)) !== null && _handler$input$parse !== void 0 ? _handler$input$parse : null;
210
+ yield res.send({
211
+ success: true,
212
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
213
+ data: yield handler.run({
214
+ ctx: context,
215
+ input
216
+ }),
217
+ message: 'OK'
218
+ });
219
+ });
220
+
221
+ return function (_x4, _x5) {
222
+ return _ref2.apply(this, arguments);
223
+ };
224
+ }());
225
+ return app;
226
+ }
227
+
228
+ exports.KaitoError = KaitoError;
229
+ exports.Router = Router;
230
+ exports.createGetContext = createGetContext;
231
+ exports.createRouter = createRouter;
232
+ exports.createServer = createServer;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./kaito-http-core.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./kaito-http-core.cjs.dev.js");
7
+ }
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var fastify = require('fastify');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
8
+
9
+ var fastify__default = /*#__PURE__*/_interopDefault(fastify);
10
+
11
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
12
+ try {
13
+ var info = gen[key](arg);
14
+ var value = info.value;
15
+ } catch (error) {
16
+ reject(error);
17
+ return;
18
+ }
19
+
20
+ if (info.done) {
21
+ resolve(value);
22
+ } else {
23
+ Promise.resolve(value).then(_next, _throw);
24
+ }
25
+ }
26
+
27
+ function _asyncToGenerator(fn) {
28
+ return function () {
29
+ var self = this,
30
+ args = arguments;
31
+ return new Promise(function (resolve, reject) {
32
+ var gen = fn.apply(self, args);
33
+
34
+ function _next(value) {
35
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
36
+ }
37
+
38
+ function _throw(err) {
39
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
40
+ }
41
+
42
+ _next(undefined);
43
+ });
44
+ };
45
+ }
46
+
47
+ function _defineProperty(obj, key, value) {
48
+ if (key in obj) {
49
+ Object.defineProperty(obj, key, {
50
+ value: value,
51
+ enumerable: true,
52
+ configurable: true,
53
+ writable: true
54
+ });
55
+ } else {
56
+ obj[key] = value;
57
+ }
58
+
59
+ return obj;
60
+ }
61
+
62
+ function ownKeys(object, enumerableOnly) {
63
+ var keys = Object.keys(object);
64
+
65
+ if (Object.getOwnPropertySymbols) {
66
+ var symbols = Object.getOwnPropertySymbols(object);
67
+
68
+ if (enumerableOnly) {
69
+ symbols = symbols.filter(function (sym) {
70
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
71
+ });
72
+ }
73
+
74
+ keys.push.apply(keys, symbols);
75
+ }
76
+
77
+ return keys;
78
+ }
79
+
80
+ function _objectSpread2(target) {
81
+ for (var i = 1; i < arguments.length; i++) {
82
+ var source = arguments[i] != null ? arguments[i] : {};
83
+
84
+ if (i % 2) {
85
+ ownKeys(Object(source), true).forEach(function (key) {
86
+ _defineProperty(target, key, source[key]);
87
+ });
88
+ } else if (Object.getOwnPropertyDescriptors) {
89
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
90
+ } else {
91
+ ownKeys(Object(source)).forEach(function (key) {
92
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
93
+ });
94
+ }
95
+ }
96
+
97
+ return target;
98
+ }
99
+
100
+ exports.Method = void 0;
101
+
102
+ (function (Method) {
103
+ Method["GET"] = "GET";
104
+ Method["POST"] = "POST";
105
+ Method["PATCH"] = "PATCH";
106
+ Method["DELETE"] = "DELETE";
107
+ })(exports.Method || (exports.Method = {}));
108
+
109
+ function createGetContext(getContext) {
110
+ return getContext;
111
+ }
112
+ class Router {
113
+ constructor(procs) {
114
+ _defineProperty(this, "create", method => (name, proc) => {
115
+ return new Router(_objectSpread2(_objectSpread2({}, this.procs), {}, {
116
+ [name]: _objectSpread2(_objectSpread2({}, proc), {}, {
117
+ method,
118
+ name
119
+ })
120
+ }));
121
+ });
122
+
123
+ _defineProperty(this, "merge", router => new Router(_objectSpread2(_objectSpread2({}, this.procs), router.getProcs())));
124
+
125
+ _defineProperty(this, "get", this.create(exports.Method.GET));
126
+
127
+ _defineProperty(this, "post", this.create(exports.Method.POST));
128
+
129
+ _defineProperty(this, "patch", this.create(exports.Method.PATCH));
130
+
131
+ _defineProperty(this, "delete", this.create(exports.Method.DELETE));
132
+
133
+ this.procs = procs;
134
+ }
135
+
136
+ getProcs() {
137
+ return this.procs;
138
+ }
139
+
140
+ }
141
+ class KaitoError extends Error {
142
+ constructor(code, message, cause) {
143
+ super(message);
144
+ this.code = code;
145
+ this.cause = cause;
146
+ }
147
+
148
+ }
149
+ function createRouter() {
150
+ return new Router({});
151
+ }
152
+ function createServer(config) {
153
+ var tree = config.router.getProcs();
154
+ var app = fastify__default["default"]();
155
+ app.setErrorHandler( /*#__PURE__*/function () {
156
+ var _ref = _asyncToGenerator(function* (error, req, res) {
157
+ if (error instanceof KaitoError) {
158
+ yield res.status(error.code).send({
159
+ success: false,
160
+ data: null,
161
+ message: error.message
162
+ });
163
+ return;
164
+ }
165
+
166
+ var {
167
+ code,
168
+ message
169
+ } = yield config.onError({
170
+ error,
171
+ req,
172
+ res
173
+ }).catch(() => ({
174
+ code: 500,
175
+ message: 'Something went wrong'
176
+ }));
177
+ yield res.status(code).send({
178
+ success: false,
179
+ data: null,
180
+ message
181
+ });
182
+ });
183
+
184
+ return function (_x, _x2, _x3) {
185
+ return _ref.apply(this, arguments);
186
+ };
187
+ }());
188
+ app.all('*', /*#__PURE__*/function () {
189
+ var _ref2 = _asyncToGenerator(function* (req, res) {
190
+ var _handler$input$parse, _handler$input;
191
+
192
+ var logMessage = "".concat(req.hostname, " ").concat(req.method, " ").concat(req.routerPath);
193
+
194
+ if (config.log === undefined) {
195
+ console.log(logMessage);
196
+ } else if (config.log) {
197
+ config.log(logMessage);
198
+ }
199
+
200
+ var url = new URL("".concat(req.protocol, "://").concat(req.hostname).concat(req.url));
201
+ var handler = tree[url.pathname];
202
+
203
+ if (!handler) {
204
+ throw new KaitoError(404, "Cannot ".concat(req.method, " this route."));
205
+ }
206
+
207
+ var context = yield config.getContext(req, res); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
208
+
209
+ var input = (_handler$input$parse = (_handler$input = handler.input) === null || _handler$input === void 0 ? void 0 : _handler$input.parse(req.method === 'GET' ? req.query : req.body)) !== null && _handler$input$parse !== void 0 ? _handler$input$parse : null;
210
+ yield res.send({
211
+ success: true,
212
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
213
+ data: yield handler.run({
214
+ ctx: context,
215
+ input
216
+ }),
217
+ message: 'OK'
218
+ });
219
+ });
220
+
221
+ return function (_x4, _x5) {
222
+ return _ref2.apply(this, arguments);
223
+ };
224
+ }());
225
+ return app;
226
+ }
227
+
228
+ exports.KaitoError = KaitoError;
229
+ exports.Router = Router;
230
+ exports.createGetContext = createGetContext;
231
+ exports.createRouter = createRouter;
232
+ exports.createServer = createServer;