@kaito-http/core 3.0.0-beta.7 → 3.0.1
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.cjs +344 -0
- package/dist/index.d.cts +255 -0
- package/dist/index.d.ts +166 -148
- package/dist/index.js +220 -301
- package/dist/stream/stream.cjs +134 -0
- package/dist/stream/stream.d.cts +36 -0
- package/dist/stream/stream.d.ts +36 -0
- package/dist/stream/stream.js +105 -0
- package/package.json +24 -15
- package/src/error.ts +26 -0
- package/src/handler.ts +96 -0
- package/src/head.ts +83 -0
- package/src/index.ts +7 -0
- package/src/request.ts +47 -0
- package/src/route.ts +52 -0
- package/src/router/router.test.ts +269 -0
- package/src/router/router.ts +264 -0
- package/src/router/types.ts +1 -0
- package/src/stream/stream.ts +156 -0
- package/src/util.ts +83 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/stream/stream.ts
|
|
21
|
+
var stream_exports = {};
|
|
22
|
+
__export(stream_exports, {
|
|
23
|
+
KaitoSSEResponse: () => KaitoSSEResponse,
|
|
24
|
+
SSEController: () => SSEController,
|
|
25
|
+
sse: () => sse,
|
|
26
|
+
sseEventToString: () => sseEventToString,
|
|
27
|
+
sseFromAnyReadable: () => sseFromAnyReadable
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(stream_exports);
|
|
30
|
+
var KaitoSSEResponse = class extends Response {
|
|
31
|
+
constructor(body, init) {
|
|
32
|
+
const headers = new Headers(init?.headers);
|
|
33
|
+
headers.set("Content-Type", "text/event-stream");
|
|
34
|
+
headers.set("Cache-Control", "no-cache");
|
|
35
|
+
headers.set("Connection", "keep-alive");
|
|
36
|
+
super(body, {
|
|
37
|
+
...init,
|
|
38
|
+
headers
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async *[Symbol.asyncIterator]() {
|
|
42
|
+
for await (const chunk of this.body) {
|
|
43
|
+
yield chunk;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
function sseEventToString(event) {
|
|
48
|
+
let result = "";
|
|
49
|
+
if (event.event) {
|
|
50
|
+
result += `event:${event.event}
|
|
51
|
+
`;
|
|
52
|
+
}
|
|
53
|
+
if (event.id) {
|
|
54
|
+
result += `id:${event.id}
|
|
55
|
+
`;
|
|
56
|
+
}
|
|
57
|
+
if (event.retry) {
|
|
58
|
+
result += `retry:${event.retry}
|
|
59
|
+
`;
|
|
60
|
+
}
|
|
61
|
+
if (event.data !== void 0) {
|
|
62
|
+
result += `data:${JSON.stringify(event.data)}`;
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
var SSEController = class {
|
|
67
|
+
controller;
|
|
68
|
+
constructor(controller) {
|
|
69
|
+
this.controller = controller;
|
|
70
|
+
}
|
|
71
|
+
enqueue(event) {
|
|
72
|
+
this.controller.enqueue(sseEventToString(event) + "\n\n");
|
|
73
|
+
}
|
|
74
|
+
close() {
|
|
75
|
+
this.controller.close();
|
|
76
|
+
}
|
|
77
|
+
[Symbol.dispose]() {
|
|
78
|
+
this.close();
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
function sseFromSource(source) {
|
|
82
|
+
const start = source.start;
|
|
83
|
+
const pull = source.pull;
|
|
84
|
+
const cancel = source.cancel;
|
|
85
|
+
const readable = new ReadableStream({
|
|
86
|
+
...cancel ? { cancel } : {},
|
|
87
|
+
...start ? {
|
|
88
|
+
start: async (controller) => {
|
|
89
|
+
await start(new SSEController(controller));
|
|
90
|
+
}
|
|
91
|
+
} : {},
|
|
92
|
+
...pull ? {
|
|
93
|
+
pull: async (controller) => {
|
|
94
|
+
await pull(new SSEController(controller));
|
|
95
|
+
}
|
|
96
|
+
} : {}
|
|
97
|
+
});
|
|
98
|
+
return new KaitoSSEResponse(readable);
|
|
99
|
+
}
|
|
100
|
+
function sse(source) {
|
|
101
|
+
const evaluated = typeof source === "function" ? source() : source;
|
|
102
|
+
if ("next" in evaluated) {
|
|
103
|
+
const generator = evaluated;
|
|
104
|
+
return sseFromSource({
|
|
105
|
+
async start(controller) {
|
|
106
|
+
try {
|
|
107
|
+
for await (const event of generator) {
|
|
108
|
+
controller.enqueue(event);
|
|
109
|
+
}
|
|
110
|
+
} finally {
|
|
111
|
+
controller.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
} else {
|
|
116
|
+
return sseFromSource(evaluated);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function sseFromAnyReadable(stream, transform) {
|
|
120
|
+
const transformer = new TransformStream({
|
|
121
|
+
transform: (chunk, controller) => {
|
|
122
|
+
controller.enqueue(transform(chunk));
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
return sse(stream.pipeThrough(transformer));
|
|
126
|
+
}
|
|
127
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
128
|
+
0 && (module.exports = {
|
|
129
|
+
KaitoSSEResponse,
|
|
130
|
+
SSEController,
|
|
131
|
+
sse,
|
|
132
|
+
sseEventToString,
|
|
133
|
+
sseFromAnyReadable
|
|
134
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
declare class KaitoSSEResponse<_T> extends Response {
|
|
2
|
+
constructor(body: ReadableStream<string>, init?: ResponseInit);
|
|
3
|
+
[Symbol.asyncIterator](): AsyncGenerator<Uint8Array<ArrayBufferLike>, void, unknown>;
|
|
4
|
+
}
|
|
5
|
+
type SSEEvent<T, E extends string> = ({
|
|
6
|
+
data: T;
|
|
7
|
+
event?: E | undefined;
|
|
8
|
+
} | {
|
|
9
|
+
data?: T | undefined;
|
|
10
|
+
event: E;
|
|
11
|
+
}) & {
|
|
12
|
+
retry?: number;
|
|
13
|
+
id?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Converts an SSE Event into a string, ready for sending to the client
|
|
17
|
+
* @param event The SSE Event
|
|
18
|
+
* @returns A stringified version
|
|
19
|
+
*/
|
|
20
|
+
declare function sseEventToString(event: SSEEvent<unknown, string>): string;
|
|
21
|
+
declare class SSEController<U, E extends string> implements Disposable {
|
|
22
|
+
private readonly controller;
|
|
23
|
+
constructor(controller: ReadableStreamDefaultController<string>);
|
|
24
|
+
enqueue(event: SSEEvent<U, E>): void;
|
|
25
|
+
close(): void;
|
|
26
|
+
[Symbol.dispose](): void;
|
|
27
|
+
}
|
|
28
|
+
interface SSESource<U, E extends string> {
|
|
29
|
+
cancel?: UnderlyingSourceCancelCallback;
|
|
30
|
+
start?(controller: SSEController<U, E>): Promise<void>;
|
|
31
|
+
pull?(controller: SSEController<U, E>): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
declare function sse<U, E extends string, T extends SSEEvent<U, E>>(source: SSESource<U, E> | AsyncGenerator<T, unknown, unknown> | (() => AsyncGenerator<T, unknown, unknown>)): KaitoSSEResponse<T>;
|
|
34
|
+
declare function sseFromAnyReadable<R, U, E extends string>(stream: ReadableStream<R>, transform: (chunk: R) => SSEEvent<U, E>): KaitoSSEResponse<SSEEvent<U, E>>;
|
|
35
|
+
|
|
36
|
+
export { KaitoSSEResponse, SSEController, type SSEEvent, type SSESource, sse, sseEventToString, sseFromAnyReadable };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
declare class KaitoSSEResponse<_T> extends Response {
|
|
2
|
+
constructor(body: ReadableStream<string>, init?: ResponseInit);
|
|
3
|
+
[Symbol.asyncIterator](): AsyncGenerator<Uint8Array<ArrayBufferLike>, void, unknown>;
|
|
4
|
+
}
|
|
5
|
+
type SSEEvent<T, E extends string> = ({
|
|
6
|
+
data: T;
|
|
7
|
+
event?: E | undefined;
|
|
8
|
+
} | {
|
|
9
|
+
data?: T | undefined;
|
|
10
|
+
event: E;
|
|
11
|
+
}) & {
|
|
12
|
+
retry?: number;
|
|
13
|
+
id?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Converts an SSE Event into a string, ready for sending to the client
|
|
17
|
+
* @param event The SSE Event
|
|
18
|
+
* @returns A stringified version
|
|
19
|
+
*/
|
|
20
|
+
declare function sseEventToString(event: SSEEvent<unknown, string>): string;
|
|
21
|
+
declare class SSEController<U, E extends string> implements Disposable {
|
|
22
|
+
private readonly controller;
|
|
23
|
+
constructor(controller: ReadableStreamDefaultController<string>);
|
|
24
|
+
enqueue(event: SSEEvent<U, E>): void;
|
|
25
|
+
close(): void;
|
|
26
|
+
[Symbol.dispose](): void;
|
|
27
|
+
}
|
|
28
|
+
interface SSESource<U, E extends string> {
|
|
29
|
+
cancel?: UnderlyingSourceCancelCallback;
|
|
30
|
+
start?(controller: SSEController<U, E>): Promise<void>;
|
|
31
|
+
pull?(controller: SSEController<U, E>): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
declare function sse<U, E extends string, T extends SSEEvent<U, E>>(source: SSESource<U, E> | AsyncGenerator<T, unknown, unknown> | (() => AsyncGenerator<T, unknown, unknown>)): KaitoSSEResponse<T>;
|
|
34
|
+
declare function sseFromAnyReadable<R, U, E extends string>(stream: ReadableStream<R>, transform: (chunk: R) => SSEEvent<U, E>): KaitoSSEResponse<SSEEvent<U, E>>;
|
|
35
|
+
|
|
36
|
+
export { KaitoSSEResponse, SSEController, type SSEEvent, type SSESource, sse, sseEventToString, sseFromAnyReadable };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// src/stream/stream.ts
|
|
2
|
+
var KaitoSSEResponse = class extends Response {
|
|
3
|
+
constructor(body, init) {
|
|
4
|
+
const headers = new Headers(init?.headers);
|
|
5
|
+
headers.set("Content-Type", "text/event-stream");
|
|
6
|
+
headers.set("Cache-Control", "no-cache");
|
|
7
|
+
headers.set("Connection", "keep-alive");
|
|
8
|
+
super(body, {
|
|
9
|
+
...init,
|
|
10
|
+
headers
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
async *[Symbol.asyncIterator]() {
|
|
14
|
+
for await (const chunk of this.body) {
|
|
15
|
+
yield chunk;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
function sseEventToString(event) {
|
|
20
|
+
let result = "";
|
|
21
|
+
if (event.event) {
|
|
22
|
+
result += `event:${event.event}
|
|
23
|
+
`;
|
|
24
|
+
}
|
|
25
|
+
if (event.id) {
|
|
26
|
+
result += `id:${event.id}
|
|
27
|
+
`;
|
|
28
|
+
}
|
|
29
|
+
if (event.retry) {
|
|
30
|
+
result += `retry:${event.retry}
|
|
31
|
+
`;
|
|
32
|
+
}
|
|
33
|
+
if (event.data !== void 0) {
|
|
34
|
+
result += `data:${JSON.stringify(event.data)}`;
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
var SSEController = class {
|
|
39
|
+
controller;
|
|
40
|
+
constructor(controller) {
|
|
41
|
+
this.controller = controller;
|
|
42
|
+
}
|
|
43
|
+
enqueue(event) {
|
|
44
|
+
this.controller.enqueue(sseEventToString(event) + "\n\n");
|
|
45
|
+
}
|
|
46
|
+
close() {
|
|
47
|
+
this.controller.close();
|
|
48
|
+
}
|
|
49
|
+
[Symbol.dispose]() {
|
|
50
|
+
this.close();
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
function sseFromSource(source) {
|
|
54
|
+
const start = source.start;
|
|
55
|
+
const pull = source.pull;
|
|
56
|
+
const cancel = source.cancel;
|
|
57
|
+
const readable = new ReadableStream({
|
|
58
|
+
...cancel ? { cancel } : {},
|
|
59
|
+
...start ? {
|
|
60
|
+
start: async (controller) => {
|
|
61
|
+
await start(new SSEController(controller));
|
|
62
|
+
}
|
|
63
|
+
} : {},
|
|
64
|
+
...pull ? {
|
|
65
|
+
pull: async (controller) => {
|
|
66
|
+
await pull(new SSEController(controller));
|
|
67
|
+
}
|
|
68
|
+
} : {}
|
|
69
|
+
});
|
|
70
|
+
return new KaitoSSEResponse(readable);
|
|
71
|
+
}
|
|
72
|
+
function sse(source) {
|
|
73
|
+
const evaluated = typeof source === "function" ? source() : source;
|
|
74
|
+
if ("next" in evaluated) {
|
|
75
|
+
const generator = evaluated;
|
|
76
|
+
return sseFromSource({
|
|
77
|
+
async start(controller) {
|
|
78
|
+
try {
|
|
79
|
+
for await (const event of generator) {
|
|
80
|
+
controller.enqueue(event);
|
|
81
|
+
}
|
|
82
|
+
} finally {
|
|
83
|
+
controller.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
} else {
|
|
88
|
+
return sseFromSource(evaluated);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function sseFromAnyReadable(stream, transform) {
|
|
92
|
+
const transformer = new TransformStream({
|
|
93
|
+
transform: (chunk, controller) => {
|
|
94
|
+
controller.enqueue(transform(chunk));
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
return sse(stream.pipeThrough(transformer));
|
|
98
|
+
}
|
|
99
|
+
export {
|
|
100
|
+
KaitoSSEResponse,
|
|
101
|
+
SSEController,
|
|
102
|
+
sse,
|
|
103
|
+
sseEventToString,
|
|
104
|
+
sseFromAnyReadable
|
|
105
|
+
};
|
package/package.json
CHANGED
|
@@ -1,15 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaito-http/core",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"author": "Alistair Smith <hi@alistair.sh>",
|
|
6
6
|
"description": "Functional HTTP Framework for TypeScript",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"build": "tsup"
|
|
8
|
+
"build": "tsup",
|
|
9
|
+
"attw": "attw --profile node16 --pack .",
|
|
10
|
+
"test": "node --test --import=tsx ./src/**/*.test.ts"
|
|
9
11
|
},
|
|
10
12
|
"exports": {
|
|
11
13
|
"./package.json": "./package.json",
|
|
12
|
-
".":
|
|
14
|
+
".": {
|
|
15
|
+
"import": {
|
|
16
|
+
"types": "./src/index.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"require": "./dist/index.cjs"
|
|
20
|
+
},
|
|
21
|
+
"./stream": {
|
|
22
|
+
"import": {
|
|
23
|
+
"types": "./src/stream/stream.ts",
|
|
24
|
+
"default": "./dist/stream/stream.js"
|
|
25
|
+
},
|
|
26
|
+
"require": "./dist/stream/stream.cjs"
|
|
27
|
+
}
|
|
13
28
|
},
|
|
14
29
|
"homepage": "https://github.com/kaito-http/kaito",
|
|
15
30
|
"repository": "https://github.com/kaito-http/kaito",
|
|
@@ -20,24 +35,18 @@
|
|
|
20
35
|
],
|
|
21
36
|
"license": "MIT",
|
|
22
37
|
"devDependencies": {
|
|
23
|
-
"@
|
|
24
|
-
"@types/
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"typescript": "^5.6.2"
|
|
38
|
+
"@arethetypeswrong/cli": "^0.17.2",
|
|
39
|
+
"@types/node": "^22.10.2",
|
|
40
|
+
"tsup": "^8.3.5",
|
|
41
|
+
"typescript": "^5.7.2"
|
|
28
42
|
},
|
|
29
43
|
"files": [
|
|
30
44
|
"package.json",
|
|
31
45
|
"README.md",
|
|
32
|
-
"dist"
|
|
46
|
+
"dist",
|
|
47
|
+
"src"
|
|
33
48
|
],
|
|
34
49
|
"bugs": {
|
|
35
50
|
"url": "https://github.com/kaito-http/kaito/issues"
|
|
36
|
-
},
|
|
37
|
-
"dependencies": {
|
|
38
|
-
"content-type": "^1.0.5",
|
|
39
|
-
"cookie": "^0.6.0",
|
|
40
|
-
"find-my-way": "^9.1.0",
|
|
41
|
-
"raw-body": "^3.0.0"
|
|
42
51
|
}
|
|
43
52
|
}
|
package/src/error.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export class WrappedError<T> extends Error {
|
|
2
|
+
public static maybe<T>(maybeError: T) {
|
|
3
|
+
if (maybeError instanceof Error) {
|
|
4
|
+
return maybeError;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
return WrappedError.from(maybeError);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
public static from<T>(data: T) {
|
|
11
|
+
return new WrappedError(data);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
private constructor(public readonly data: T) {
|
|
15
|
+
super('Something was thrown, but it was not an instance of Error, so a WrappedError was created.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class KaitoError extends Error {
|
|
20
|
+
constructor(
|
|
21
|
+
public readonly status: number,
|
|
22
|
+
message: string,
|
|
23
|
+
) {
|
|
24
|
+
super(message);
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/handler.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type {KaitoError} from './error.ts';
|
|
2
|
+
import type {KaitoRequest} from './request.ts';
|
|
3
|
+
import type {Router} from './router/router.ts';
|
|
4
|
+
import type {GetContext} from './util.ts';
|
|
5
|
+
|
|
6
|
+
export type HandlerConfig<ContextFrom> = {
|
|
7
|
+
/**
|
|
8
|
+
* The root router to mount on this handler.
|
|
9
|
+
*/
|
|
10
|
+
router: Router<ContextFrom, unknown, any>;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A function that is called to get the context for a request.
|
|
14
|
+
*
|
|
15
|
+
* This is useful for things like authentication, to pass in a database connection, etc.
|
|
16
|
+
*
|
|
17
|
+
* It's fine for this function to throw; if it does, the error is passed to the `onError` function.
|
|
18
|
+
*/
|
|
19
|
+
getContext: GetContext<ContextFrom>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A function that is called when an error occurs inside a route handler.
|
|
23
|
+
*
|
|
24
|
+
* The result of this function is used to determine the response status and message, and is
|
|
25
|
+
* always sent to the client. You could include logic to check for production vs development
|
|
26
|
+
* environments here, and this would also be a good place to include error tracking
|
|
27
|
+
* like Sentry or Rollbar.
|
|
28
|
+
*
|
|
29
|
+
* @param arg - The error thrown, and the KaitoRequest instance
|
|
30
|
+
* @returns A KaitoError or an object with a status and message
|
|
31
|
+
*/
|
|
32
|
+
onError: (arg: {error: Error; req: KaitoRequest}) => Promise<KaitoError | {status: number; message: string}>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A function that is called before every request. Most useful for bailing out early in the case of an OPTIONS request.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* before: async req => {
|
|
40
|
+
* if (req.method === 'OPTIONS') {
|
|
41
|
+
* return new Response(null, {status: 204});
|
|
42
|
+
* }
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
before?: (req: Request) => Promise<Response | void | undefined>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Transforms the response before it is sent to the client. Very useful for settings headers like CORS.
|
|
50
|
+
*
|
|
51
|
+
* You can also return a new response in this function, or just mutate the current one.
|
|
52
|
+
*
|
|
53
|
+
* This function WILL receive the result of `.before()` if you return a response from it. This means
|
|
54
|
+
* you only need to define headers in a single place.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* transform: async (req, res) => {
|
|
59
|
+
* res.headers.set('Access-Control-Allow-Origin', 'http://localhost:3000');
|
|
60
|
+
* res.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
|
61
|
+
* res.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
62
|
+
* res.headers.set('Access-Control-Max-Age', '86400');
|
|
63
|
+
* res.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
64
|
+
* }
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
transform?: (req: Request, res: Response) => Promise<Response | void | undefined>;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export function createKaitoHandler<Context>(config: HandlerConfig<Context>) {
|
|
71
|
+
const handle = config.router.freeze(config);
|
|
72
|
+
|
|
73
|
+
return async (request: Request): Promise<Response> => {
|
|
74
|
+
if (config.before) {
|
|
75
|
+
const result = await config.before(request);
|
|
76
|
+
|
|
77
|
+
if (result instanceof Response) {
|
|
78
|
+
if (config.transform) {
|
|
79
|
+
const result2 = await config.transform(request, result);
|
|
80
|
+
if (result2 instanceof Response) return result;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const response = await handle(request);
|
|
88
|
+
|
|
89
|
+
if (config.transform) {
|
|
90
|
+
const result = await config.transform(request, response);
|
|
91
|
+
if (result instanceof Response) return result;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return response;
|
|
95
|
+
};
|
|
96
|
+
}
|
package/src/head.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type {APIResponse} from './util.ts';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* This class is merely a wrapper around a `Headers` object and a status code.
|
|
5
|
+
* It's used while the router is executing a route to store any mutations to the status
|
|
6
|
+
* code or headers that the developer may want to make.
|
|
7
|
+
*
|
|
8
|
+
* This exists because there's otherwise no way to indicate back to Kaito that
|
|
9
|
+
* the developer wants to change the status code or headers.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* const response = new KaitoHead();
|
|
14
|
+
*
|
|
15
|
+
* response.status(200);
|
|
16
|
+
* response.headers.set('Content-Type', 'application/json');
|
|
17
|
+
*
|
|
18
|
+
* console.log(response.headers); // Headers {'content-type': 'application/json'}
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export class KaitoHead {
|
|
22
|
+
private _headers: Headers | null;
|
|
23
|
+
private _status: number;
|
|
24
|
+
|
|
25
|
+
public constructor() {
|
|
26
|
+
this._headers = null;
|
|
27
|
+
this._status = 200;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public get headers() {
|
|
31
|
+
if (this._headers === null) {
|
|
32
|
+
this._headers = new Headers();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return this._headers;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Gets the status code of this KaitoHead instance
|
|
40
|
+
* @returns The status code
|
|
41
|
+
*/
|
|
42
|
+
public status(): number;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Sets the status code of this KaitoHead instance
|
|
46
|
+
* @param status The status code to set
|
|
47
|
+
* @returns This KaitoHead instance
|
|
48
|
+
*/
|
|
49
|
+
public status(status: number): this;
|
|
50
|
+
|
|
51
|
+
public status(status?: number) {
|
|
52
|
+
if (status === undefined) {
|
|
53
|
+
return this._status;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
this._status = status;
|
|
57
|
+
return this;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Turn this KaitoHead instance into a Response instance
|
|
62
|
+
* @param body The Kaito JSON format to be sent as the response body
|
|
63
|
+
* @returns A Response instance, ready to be sent
|
|
64
|
+
*/
|
|
65
|
+
public toResponse<T>(body: APIResponse<T>): Response {
|
|
66
|
+
const init: ResponseInit = {
|
|
67
|
+
status: this._status,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
if (this._headers) {
|
|
71
|
+
init.headers = this._headers;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return Response.json(body, init);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Whether this KaitoHead instance has been touched/modified
|
|
79
|
+
*/
|
|
80
|
+
public get touched() {
|
|
81
|
+
return this._status !== 200 || this._headers !== null;
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/index.ts
ADDED
package/src/request.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export class KaitoRequest {
|
|
2
|
+
public readonly url: URL;
|
|
3
|
+
|
|
4
|
+
private readonly _request: Request;
|
|
5
|
+
|
|
6
|
+
public constructor(url: URL, request: Request) {
|
|
7
|
+
this._request = request;
|
|
8
|
+
this.url = url;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
public get headers() {
|
|
12
|
+
return this._request.headers;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
public get method() {
|
|
16
|
+
return this._request.method;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
public async arrayBuffer(): Promise<ArrayBuffer> {
|
|
20
|
+
return this._request.arrayBuffer();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
public async blob(): Promise<Blob> {
|
|
24
|
+
return this._request.blob();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
public async formData(): Promise<FormData> {
|
|
28
|
+
return this._request.formData();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
public async bytes(): Promise<Uint8Array> {
|
|
32
|
+
const buffer = await this.arrayBuffer();
|
|
33
|
+
return new Uint8Array(buffer);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
public async json(): Promise<unknown> {
|
|
37
|
+
return this._request.json();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public async text(): Promise<string> {
|
|
41
|
+
return this._request.text();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
public get request() {
|
|
45
|
+
return this._request;
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/route.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type {KaitoMethod} from './router/types.ts';
|
|
2
|
+
import type {ExtractRouteParams, InferParsable, Parsable} from './util.ts';
|
|
3
|
+
|
|
4
|
+
export type RouteArgument<Path extends string, Context, QueryOutput, BodyOutput> = {
|
|
5
|
+
ctx: Context;
|
|
6
|
+
body: BodyOutput;
|
|
7
|
+
query: QueryOutput;
|
|
8
|
+
params: ExtractRouteParams<Path>;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type AnyQueryDefinition = Record<string, Parsable<any, string | undefined>>;
|
|
12
|
+
|
|
13
|
+
export type Through<From, To> = (context: From) => Promise<To>;
|
|
14
|
+
|
|
15
|
+
export type Route<
|
|
16
|
+
// Router context
|
|
17
|
+
ContextFrom,
|
|
18
|
+
ContextTo,
|
|
19
|
+
// Route information
|
|
20
|
+
Result,
|
|
21
|
+
Path extends string,
|
|
22
|
+
Method extends KaitoMethod,
|
|
23
|
+
// Schemas
|
|
24
|
+
Query extends AnyQueryDefinition,
|
|
25
|
+
Body extends Parsable,
|
|
26
|
+
> = {
|
|
27
|
+
through: Through<ContextFrom, ContextTo>;
|
|
28
|
+
body?: Body;
|
|
29
|
+
query?: Query;
|
|
30
|
+
path: Path;
|
|
31
|
+
method: Method;
|
|
32
|
+
run(
|
|
33
|
+
arg: RouteArgument<
|
|
34
|
+
Path,
|
|
35
|
+
ContextTo,
|
|
36
|
+
{
|
|
37
|
+
[Key in keyof Query]: InferParsable<Query[Key]>['output'];
|
|
38
|
+
},
|
|
39
|
+
InferParsable<Body>['output']
|
|
40
|
+
>,
|
|
41
|
+
): Promise<Result>;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type AnyRoute<ContextFrom = any, ContextTo = any> = Route<
|
|
45
|
+
ContextFrom,
|
|
46
|
+
ContextTo,
|
|
47
|
+
any,
|
|
48
|
+
any,
|
|
49
|
+
any,
|
|
50
|
+
AnyQueryDefinition,
|
|
51
|
+
any
|
|
52
|
+
>;
|