@pollium/readable 0.0.0-stage → 0.2.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/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorate.js +8 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorateMetadata.js +5 -0
- package/dist/app/Application.d.ts +34 -0
- package/dist/app/Application.js +136 -0
- package/dist/app/abort.d.ts +8 -0
- package/dist/app/abort.js +16 -0
- package/dist/app/compression.d.ts +2 -0
- package/dist/app/compression.js +35 -0
- package/dist/app/config.d.ts +45 -0
- package/dist/app/config.js +55 -0
- package/dist/app/discovery.d.ts +27 -0
- package/dist/app/discovery.js +75 -0
- package/dist/app/errors.d.ts +22 -0
- package/dist/app/errors.js +58 -0
- package/dist/app/logger.d.ts +20 -0
- package/dist/app/logger.js +40 -0
- package/dist/app/metadata.d.ts +5 -0
- package/dist/app/metadata.js +16 -0
- package/dist/app/redis.d.ts +4 -0
- package/dist/app/redis.js +24 -0
- package/dist/auth/credentials.d.ts +6 -0
- package/dist/auth/credentials.js +24 -0
- package/dist/auth/guards.d.ts +11 -0
- package/dist/auth/guards.js +44 -0
- package/dist/auth/params.d.ts +8 -0
- package/dist/auth/params.js +19 -0
- package/dist/auth/secrets.d.ts +6 -0
- package/dist/auth/secrets.js +38 -0
- package/dist/auth/sessions.d.ts +32 -0
- package/dist/auth/sessions.js +49 -0
- package/dist/database/data-source.d.ts +7 -0
- package/dist/database/data-source.js +22 -0
- package/dist/database/models.d.ts +16 -0
- package/dist/database/models.js +72 -0
- package/dist/database/queries.d.ts +26 -0
- package/dist/database/queries.js +56 -0
- package/dist/events/Broadcast.d.ts +8 -0
- package/dist/events/Broadcast.js +42 -0
- package/dist/events/EventBus.d.ts +23 -0
- package/dist/events/EventBus.js +115 -0
- package/dist/gateway/ConnectionRegistry.d.ts +25 -0
- package/dist/gateway/ConnectionRegistry.js +68 -0
- package/dist/gateway/Gateway.d.ts +15 -0
- package/dist/gateway/Gateway.js +135 -0
- package/dist/http/Controller.d.ts +29 -0
- package/dist/http/Controller.js +97 -0
- package/dist/http/auto-validate-body.d.ts +8 -0
- package/dist/http/auto-validate-body.js +16 -0
- package/dist/http/call.d.ts +24 -0
- package/dist/http/call.js +66 -0
- package/dist/http/middleware.d.ts +21 -0
- package/dist/http/middleware.js +39 -0
- package/dist/http/org-context.d.ts +6 -0
- package/dist/http/org-context.js +23 -0
- package/dist/http/params.d.ts +40 -0
- package/dist/http/params.js +95 -0
- package/dist/http/responses.d.ts +20 -0
- package/dist/http/responses.js +29 -0
- package/dist/queues/BaseQueue.d.ts +15 -0
- package/dist/queues/BaseQueue.js +69 -0
- package/dist/queues/QueueProducer.d.ts +9 -0
- package/dist/queues/QueueProducer.js +21 -0
- package/dist/storage/ObjectStorage.d.ts +37 -0
- package/dist/storage/ObjectStorage.js +170 -0
- package/dist/testing/harness.d.ts +25 -0
- package/dist/testing/harness.js +46 -0
- package/dist/testing/rate-limit.d.ts +2 -0
- package/dist/testing/rate-limit.js +4 -0
- package/dist/testing/request.d.ts +21 -0
- package/dist/testing/request.js +41 -0
- package/dist/tools/ToolGroup.d.ts +33 -0
- package/dist/tools/ToolGroup.js +30 -0
- package/package.json +62 -3
- package/README.md +0 -3
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// lib/gateway/ConnectionRegistry.ts
|
|
2
|
+
var ConnectionsRegistry = class {
|
|
3
|
+
#sockets = /* @__PURE__ */ new Set();
|
|
4
|
+
#rooms = /* @__PURE__ */ new Map();
|
|
5
|
+
#memberships = /* @__PURE__ */ new WeakMap();
|
|
6
|
+
#access = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
add(socket) {
|
|
8
|
+
this.#sockets.add(socket);
|
|
9
|
+
}
|
|
10
|
+
remove(socket) {
|
|
11
|
+
this.leaveAll(socket);
|
|
12
|
+
this.#sockets.delete(socket);
|
|
13
|
+
}
|
|
14
|
+
join(socket, room, access) {
|
|
15
|
+
let members = this.#rooms.get(room);
|
|
16
|
+
if (!members) {
|
|
17
|
+
members = /* @__PURE__ */ new Set();
|
|
18
|
+
this.#rooms.set(room, members);
|
|
19
|
+
}
|
|
20
|
+
members.add(socket);
|
|
21
|
+
const memberships = this.#memberships.get(socket) ?? /* @__PURE__ */ new Set();
|
|
22
|
+
memberships.add(room);
|
|
23
|
+
this.#memberships.set(socket, memberships);
|
|
24
|
+
if (access === void 0) return;
|
|
25
|
+
const granted = this.#access.get(socket) ?? /* @__PURE__ */ new Map();
|
|
26
|
+
granted.set(room, access);
|
|
27
|
+
this.#access.set(socket, granted);
|
|
28
|
+
}
|
|
29
|
+
leave(socket, room) {
|
|
30
|
+
const members = this.#rooms.get(room);
|
|
31
|
+
members?.delete(socket);
|
|
32
|
+
if (members?.size === 0) this.#rooms.delete(room);
|
|
33
|
+
this.#memberships.get(socket)?.delete(room);
|
|
34
|
+
this.#access.get(socket)?.delete(room);
|
|
35
|
+
}
|
|
36
|
+
leaveAll(socket) {
|
|
37
|
+
for (const room of this.#memberships.get(socket) ?? []) this.leave(socket, room);
|
|
38
|
+
this.#memberships.delete(socket);
|
|
39
|
+
this.#access.delete(socket);
|
|
40
|
+
}
|
|
41
|
+
async reauthorize(socket) {
|
|
42
|
+
for (const access of this.#access.get(socket)?.values() ?? []) await access();
|
|
43
|
+
}
|
|
44
|
+
has(room) {
|
|
45
|
+
return this.#rooms.has(room);
|
|
46
|
+
}
|
|
47
|
+
broadcast(message) {
|
|
48
|
+
this.#send(this.#sockets, message);
|
|
49
|
+
}
|
|
50
|
+
sendTo(socket, message) {
|
|
51
|
+
this.#send([socket], message);
|
|
52
|
+
}
|
|
53
|
+
sendToRoom(room, message) {
|
|
54
|
+
const members = this.#rooms.get(room);
|
|
55
|
+
if (members) this.#send(members, message);
|
|
56
|
+
}
|
|
57
|
+
sendToRooms(rooms, message) {
|
|
58
|
+
this.#send(new Set(rooms.flatMap((room) => [...this.#rooms.get(room) ?? []])), message);
|
|
59
|
+
}
|
|
60
|
+
#send(sockets, message) {
|
|
61
|
+
const raw = JSON.stringify(message);
|
|
62
|
+
for (const socket of sockets) socket.send(raw);
|
|
63
|
+
}
|
|
64
|
+
get size() {
|
|
65
|
+
return this.#sockets.size;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
export { ConnectionsRegistry as default };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import ConnectionsRegistry from "./ConnectionRegistry.js";
|
|
2
|
+
import { FastifyInstance } from "fastify";
|
|
3
|
+
import { WebsocketPluginOptions } from "@fastify/websocket";
|
|
4
|
+
export declare const OnConnect: () => MethodDecorator;
|
|
5
|
+
export declare const OnDisconnect: () => MethodDecorator;
|
|
6
|
+
export declare const OnMessage: (type: string) => MethodDecorator;
|
|
7
|
+
export declare const Payload: () => ParameterDecorator;
|
|
8
|
+
export declare const Socket: () => ParameterDecorator;
|
|
9
|
+
export declare const websocketOptions: WebsocketPluginOptions;
|
|
10
|
+
export declare const Channel: (path: string) => ClassDecorator;
|
|
11
|
+
export default abstract class BaseGateway {
|
|
12
|
+
#private;
|
|
13
|
+
protected readonly connections: ConnectionsRegistry;
|
|
14
|
+
register(app: FastifyInstance): void;
|
|
15
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { ClassMetadata } from "../app/metadata.js";
|
|
2
|
+
import ConnectionsRegistry from "./ConnectionRegistry.js";
|
|
3
|
+
import { createParamDecorator, getParamResolvers } from "../http/params.js";
|
|
4
|
+
import { GatewayError, RuntimeError } from "../app/errors.js";
|
|
5
|
+
import { getClassMiddleware } from "../http/middleware.js";
|
|
6
|
+
import { abortScope } from "../app/abort.js";
|
|
7
|
+
// lib/gateway/Gateway.ts
|
|
8
|
+
const channels = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
const bindings = new ClassMetadata();
|
|
10
|
+
const invocations = /* @__PURE__ */ new WeakMap();
|
|
11
|
+
const OnConnect = () => on("connect");
|
|
12
|
+
const OnDisconnect = () => on("disconnect");
|
|
13
|
+
const OnMessage = (type) => on("message", type);
|
|
14
|
+
const Payload = () => createParamDecorator((req) => invocations.get(req)?.frame);
|
|
15
|
+
const Socket = () => createParamDecorator((req) => invocations.get(req)?.socket);
|
|
16
|
+
const websocketOptions = { options: { maxPayload: 1048576 } };
|
|
17
|
+
const Channel = (path) => {
|
|
18
|
+
return (target) => {
|
|
19
|
+
channels.set(target, path);
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
const on = (event, type) => {
|
|
23
|
+
return (target, handlerName) => {
|
|
24
|
+
bindings.append(target.constructor, {
|
|
25
|
+
event,
|
|
26
|
+
type,
|
|
27
|
+
handlerName
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
var BaseGateway = class {
|
|
32
|
+
constructor() {
|
|
33
|
+
this.connections = new ConnectionsRegistry();
|
|
34
|
+
this.#authorizations = /* @__PURE__ */ new WeakMap();
|
|
35
|
+
}
|
|
36
|
+
#authorizations;
|
|
37
|
+
register(app) {
|
|
38
|
+
const path = channels.get(this.constructor);
|
|
39
|
+
if (!path) throw GatewayError.MissingChannel();
|
|
40
|
+
const guards = getClassMiddleware(this.constructor);
|
|
41
|
+
app.get(path, {
|
|
42
|
+
websocket: true,
|
|
43
|
+
preValidation: async (req, reply) => {
|
|
44
|
+
const authorize = async () => {
|
|
45
|
+
for (const guard of guards) await guard(req, reply);
|
|
46
|
+
};
|
|
47
|
+
await authorize();
|
|
48
|
+
this.#authorizations.set(req, authorize);
|
|
49
|
+
}
|
|
50
|
+
}, (socket, req) => this.#onConnection(socket, req));
|
|
51
|
+
}
|
|
52
|
+
#onConnection(socket, req) {
|
|
53
|
+
const disconnected = new AbortController();
|
|
54
|
+
this.connections.add(socket);
|
|
55
|
+
const expiry = req.sessionExpiresAt === void 0 ? void 0 : setTimeout(() => socket.close(4401, "session expired"), req.sessionExpiresAt * 1e3 - Date.now());
|
|
56
|
+
const reauthorizing = setInterval(() => {
|
|
57
|
+
this.#reauthorize(socket, req);
|
|
58
|
+
}, 3e4);
|
|
59
|
+
this.#runLifecycle("connect", socket, req);
|
|
60
|
+
socket.on("message", (raw) => {
|
|
61
|
+
abortScope.run(disconnected.signal, () => this.#dispatch(socket, req, raw.toString()));
|
|
62
|
+
});
|
|
63
|
+
socket.on("close", () => {
|
|
64
|
+
clearTimeout(expiry);
|
|
65
|
+
clearInterval(reauthorizing);
|
|
66
|
+
disconnected.abort();
|
|
67
|
+
this.connections.remove(socket);
|
|
68
|
+
this.#runLifecycle("disconnect", socket, req);
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
async #reauthorize(socket, req) {
|
|
72
|
+
try {
|
|
73
|
+
await this.#authorizations.get(req)?.();
|
|
74
|
+
await this.connections.reauthorize(socket);
|
|
75
|
+
} catch {
|
|
76
|
+
socket.close(4403, "access revoked");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
#runLifecycle(event, socket, req) {
|
|
80
|
+
for (const binding of bindings.get(this.constructor)) {
|
|
81
|
+
if (binding.event !== event) continue;
|
|
82
|
+
this.#invoke(binding.handlerName, socket, req, void 0).catch((error) => this.#fail(socket, error));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async #dispatch(socket, req, raw) {
|
|
86
|
+
const frame = this.#parseFrame(raw);
|
|
87
|
+
if (!frame) {
|
|
88
|
+
this.#fail(socket, GatewayError.MalformedFrame());
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const binding = bindings.get(this.constructor).find((candidate) => candidate.event === "message" && candidate.type === frame.type);
|
|
92
|
+
if (!binding) {
|
|
93
|
+
this.#fail(socket, GatewayError.UnknownMessageType(), frame);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const result = await this.#invoke(binding.handlerName, socket, req, frame);
|
|
98
|
+
if (result === void 0 || result === null) return;
|
|
99
|
+
socket.send(JSON.stringify({
|
|
100
|
+
type: frame.type,
|
|
101
|
+
data: result
|
|
102
|
+
}));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (abortScope.signal()?.aborted === true) return;
|
|
105
|
+
this.#fail(socket, error, frame);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
#parseFrame(raw) {
|
|
109
|
+
try {
|
|
110
|
+
const frame = JSON.parse(raw);
|
|
111
|
+
return typeof frame?.type === "string" ? frame : void 0;
|
|
112
|
+
} catch {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async #invoke(handlerName, socket, req, frame) {
|
|
117
|
+
const ctx = Object.create(req);
|
|
118
|
+
invocations.set(ctx, {
|
|
119
|
+
socket,
|
|
120
|
+
frame
|
|
121
|
+
});
|
|
122
|
+
const resolvers = getParamResolvers(this.constructor, handlerName);
|
|
123
|
+
const args = await Promise.all(resolvers.map((resolve) => resolve(ctx)));
|
|
124
|
+
return Reflect.get(this, handlerName).apply(this, args);
|
|
125
|
+
}
|
|
126
|
+
#fail(socket, error, frame) {
|
|
127
|
+
const answer = error instanceof RuntimeError ? error : GatewayError.Internal();
|
|
128
|
+
const sessionId = frame?.sessionId;
|
|
129
|
+
socket.send(JSON.stringify({
|
|
130
|
+
error: answer.message,
|
|
131
|
+
...typeof sessionId === "string" ? { sessionId } : {}
|
|
132
|
+
}));
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
export { Channel, OnConnect, OnDisconnect, OnMessage, Payload, Socket, BaseGateway as default, websocketOptions };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ClassMetadata } from "../app/metadata.js";
|
|
2
|
+
import { FastifyInstance, FastifyReply, FastifyRequest, RouteGenericInterface } from "fastify";
|
|
3
|
+
import { Endpoint, HttpMethod } from "@pollium/readable-contracts/routing";
|
|
4
|
+
export interface RouteDefinition {
|
|
5
|
+
path: string;
|
|
6
|
+
method: HttpMethod;
|
|
7
|
+
handlerName: string | symbol;
|
|
8
|
+
absolute: boolean;
|
|
9
|
+
bodyLimit?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface RouteOptions {
|
|
12
|
+
method?: HttpMethod;
|
|
13
|
+
bodyLimit?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface StatusBinding {
|
|
16
|
+
handlerName: string | symbol;
|
|
17
|
+
code: number;
|
|
18
|
+
}
|
|
19
|
+
export type Handler = (req: FastifyRequest<RouteGenericInterface>, reply: FastifyReply) => unknown;
|
|
20
|
+
export declare const routesByController: ClassMetadata<RouteDefinition>;
|
|
21
|
+
export declare const Controller: (prefix: string) => ClassDecorator;
|
|
22
|
+
export declare const getControllerPrefix: (ctor: object) => string | undefined;
|
|
23
|
+
export declare const Route: <I, O>(route: string | Endpoint<I, O>, options?: HttpMethod | RouteOptions) => MethodDecorator;
|
|
24
|
+
export declare const Status: (code: number) => MethodDecorator;
|
|
25
|
+
export declare const getStatus: (ctor: object, handlerName: string | symbol) => number | undefined;
|
|
26
|
+
export default abstract class BaseController {
|
|
27
|
+
#private;
|
|
28
|
+
register(app: FastifyInstance, prefix: string): Promise<void>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { ClassMetadata } from "../app/metadata.js";
|
|
2
|
+
import { Paginated, RawResponse, RedirectResponse } from "./responses.js";
|
|
3
|
+
import { getParamResolvers } from "./params.js";
|
|
4
|
+
import { getMiddleware, getRateLimit } from "./middleware.js";
|
|
5
|
+
import { RouteError } from "../app/errors.js";
|
|
6
|
+
// lib/http/Controller.ts
|
|
7
|
+
const prefixByController = /* @__PURE__ */ new WeakMap();
|
|
8
|
+
const statusByHandler = new ClassMetadata();
|
|
9
|
+
const routesByController = new ClassMetadata();
|
|
10
|
+
const Controller = (prefix) => {
|
|
11
|
+
return (target) => {
|
|
12
|
+
prefixByController.set(target, prefix);
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
const getControllerPrefix = (ctor) => {
|
|
16
|
+
return prefixByController.get(ctor);
|
|
17
|
+
};
|
|
18
|
+
const Route = (route, options = "GET") => {
|
|
19
|
+
return (target, handlerName) => {
|
|
20
|
+
const { method = "GET", bodyLimit } = typeof options === "string" ? { method: options } : options;
|
|
21
|
+
const definition = typeof route === "string" ? {
|
|
22
|
+
path: route,
|
|
23
|
+
method,
|
|
24
|
+
absolute: false
|
|
25
|
+
} : {
|
|
26
|
+
path: route.path,
|
|
27
|
+
method: route.method,
|
|
28
|
+
absolute: true
|
|
29
|
+
};
|
|
30
|
+
routesByController.append(target.constructor, {
|
|
31
|
+
...definition,
|
|
32
|
+
bodyLimit,
|
|
33
|
+
handlerName
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
const Status = (code) => {
|
|
38
|
+
return (target, handlerName) => {
|
|
39
|
+
statusByHandler.append(target.constructor, {
|
|
40
|
+
handlerName,
|
|
41
|
+
code
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
const getStatus = (ctor, handlerName) => {
|
|
46
|
+
return statusByHandler.get(ctor).find((binding) => binding.handlerName === handlerName)?.code;
|
|
47
|
+
};
|
|
48
|
+
var BaseController = class {
|
|
49
|
+
async register(app, prefix) {
|
|
50
|
+
const mount = async (scope) => {
|
|
51
|
+
for (const route of routesByController.get(this.constructor)) {
|
|
52
|
+
const handler = this.#wrap(route.handlerName);
|
|
53
|
+
const middlewares = getMiddleware(this.constructor, route.handlerName);
|
|
54
|
+
const url = route.absolute ? this.#relativeTo(route.path, prefix) : route.path;
|
|
55
|
+
scope.route({
|
|
56
|
+
method: route.method,
|
|
57
|
+
url,
|
|
58
|
+
bodyLimit: route.bodyLimit,
|
|
59
|
+
config: { rateLimit: getRateLimit(this.constructor, route.handlerName) },
|
|
60
|
+
preHandler: middlewares.map((mw) => async (req, reply) => await mw(req, reply)),
|
|
61
|
+
handler
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
if (prefix === "") {
|
|
66
|
+
await mount(app);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
await app.register(mount, { prefix });
|
|
70
|
+
}
|
|
71
|
+
#relativeTo(path, prefix) {
|
|
72
|
+
if (path !== prefix && !path.startsWith(`${prefix}/`)) throw RouteError.PrefixMismatch(path);
|
|
73
|
+
return path.slice(prefix.length) || "/";
|
|
74
|
+
}
|
|
75
|
+
#wrap(handlerName) {
|
|
76
|
+
const method = Reflect.get(this, handlerName).bind(this);
|
|
77
|
+
const override = getStatus(this.constructor, handlerName);
|
|
78
|
+
const resolvers = getParamResolvers(this.constructor, handlerName);
|
|
79
|
+
return async (req, reply) => {
|
|
80
|
+
const boxes = await Promise.all(Array.from(resolvers, async (resolve) => {
|
|
81
|
+
const arg = resolve === void 0 ? void 0 : resolve(req, reply);
|
|
82
|
+
return { arg: arg instanceof Promise ? await arg : arg };
|
|
83
|
+
}));
|
|
84
|
+
const result = await method(...boxes.map((box) => box.arg));
|
|
85
|
+
if (reply.sent) return;
|
|
86
|
+
if (result instanceof RawResponse) return reply.status(override ?? result.status).type(result.contentType).send(result.body);
|
|
87
|
+
if (result instanceof RedirectResponse) return reply.redirect(result.url, result.status);
|
|
88
|
+
if (result instanceof Paginated) return reply.status(override ?? 200).send({
|
|
89
|
+
data: result.items,
|
|
90
|
+
meta: result.meta
|
|
91
|
+
});
|
|
92
|
+
if (result === void 0 || result === null) return reply.status(override ?? 204).send();
|
|
93
|
+
return reply.status(override ?? 200).send({ data: result });
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
export { Controller, Route, Status, BaseController as default, getControllerPrefix, getStatus, routesByController };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// lib/http/auto-validate-body.ts
|
|
2
|
+
const autoValidateBody = () => ({
|
|
3
|
+
name: "readable:auto-validate-body",
|
|
4
|
+
enforce: "pre",
|
|
5
|
+
transform(code, id) {
|
|
6
|
+
if (!/src\/modules\/[^/?]+\/controllers\/[^/?]+\.ts(\?.*)?$/.test(id)) return null;
|
|
7
|
+
if (!code.includes("@Body()")) return null;
|
|
8
|
+
let out = code.replace(/@Body\(\)(\s+)(\w+):(\s*)(\w+)/g, "@Body(typia.misc.createValidatePrune<$4>())$1$2:$3$4");
|
|
9
|
+
if (!/from 'typia'/.test(out)) out += "\nimport typia from 'typia';\n";
|
|
10
|
+
return {
|
|
11
|
+
code: out,
|
|
12
|
+
map: null
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
export { autoValidateBody };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { RuntimeError } from "../app/errors.js";
|
|
2
|
+
import { MiddlewareFn } from "./middleware.js";
|
|
3
|
+
import { Endpoint } from "@pollium/readable-contracts/routing";
|
|
4
|
+
export interface Host {
|
|
5
|
+
url: string;
|
|
6
|
+
header: string;
|
|
7
|
+
key: string;
|
|
8
|
+
}
|
|
9
|
+
export interface CallOptions<I> {
|
|
10
|
+
path?: Record<string, string>;
|
|
11
|
+
query?: Record<string, string>;
|
|
12
|
+
body?: I;
|
|
13
|
+
}
|
|
14
|
+
export declare const CallError: Record<"Failed" | "Rejected", (detail?: string) => RuntimeError>;
|
|
15
|
+
export declare const isNotFound: (error: unknown) => boolean;
|
|
16
|
+
export declare const interpolate: (path: string, params?: Record<string, string>) => string;
|
|
17
|
+
export declare const request: <I, O>(host: Host, endpoint: Endpoint<I, O>, options?: CallOptions<I>) => Promise<Response>;
|
|
18
|
+
export declare const call: <I, O>(host: Host, endpoint: Endpoint<I, O>, options?: CallOptions<I>) => Promise<O>;
|
|
19
|
+
export declare class ServiceClient {
|
|
20
|
+
#private;
|
|
21
|
+
constructor(host: Host);
|
|
22
|
+
call<I, O>(endpoint: Endpoint<I, O>, options?: CallOptions<I>): Promise<O>;
|
|
23
|
+
}
|
|
24
|
+
export declare const ServiceKeyRoute: (header: string, expected: string) => MiddlewareFn;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { AuthError, RuntimeError, defineErrors } from "../app/errors.js";
|
|
2
|
+
import { logger } from "../app/logger.js";
|
|
3
|
+
import { timingSafeEqual } from "node:crypto";
|
|
4
|
+
// lib/http/call.ts
|
|
5
|
+
const CallError = defineErrors({
|
|
6
|
+
domain: "Call",
|
|
7
|
+
causes: {
|
|
8
|
+
Failed: 502,
|
|
9
|
+
Rejected: 502
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
const isNotFound = (error) => error instanceof RuntimeError && error.statusCode === 404;
|
|
13
|
+
const interpolate = (path, params = {}) => path.replace(/:(\w+)/g, (_, name) => encodeURIComponent(params[name] ?? ""));
|
|
14
|
+
const unwrap = (payload) => {
|
|
15
|
+
if (payload !== null && typeof payload === "object" && "data" in payload) return payload.data;
|
|
16
|
+
return payload;
|
|
17
|
+
};
|
|
18
|
+
const errorOf = async (response) => {
|
|
19
|
+
const payload = await response.json().catch(() => null);
|
|
20
|
+
if (payload !== null && typeof payload === "object" && "error" in payload && typeof payload.error === "string") return new RuntimeError(payload.error, response.status);
|
|
21
|
+
return CallError.Failed(String(response.status));
|
|
22
|
+
};
|
|
23
|
+
const rejectionOf = (host, endpoint, status) => {
|
|
24
|
+
logger.error(`${endpoint.method} ${host.url}${endpoint.path} rejected the ${host.header} service key`, null, {
|
|
25
|
+
scope: "call",
|
|
26
|
+
statusCode: status
|
|
27
|
+
});
|
|
28
|
+
return CallError.Rejected(String(status));
|
|
29
|
+
};
|
|
30
|
+
const request = async (host, endpoint, options = {}) => {
|
|
31
|
+
const path = interpolate(endpoint.path, options.path);
|
|
32
|
+
const search = options.query === void 0 ? "" : `?${new URLSearchParams(options.query)}`;
|
|
33
|
+
const response = await fetch(`${host.url}${path}${search}`, {
|
|
34
|
+
method: endpoint.method,
|
|
35
|
+
body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
|
|
36
|
+
headers: {
|
|
37
|
+
[host.header]: host.key,
|
|
38
|
+
...options.body === void 0 ? {} : { "content-type": "application/json" }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
if ([401, 403].includes(response.status)) throw rejectionOf(host, endpoint, response.status);
|
|
42
|
+
if (!response.ok) throw await errorOf(response);
|
|
43
|
+
return response;
|
|
44
|
+
};
|
|
45
|
+
const call = async (host, endpoint, options = {}) => {
|
|
46
|
+
const response = await request(host, endpoint, options);
|
|
47
|
+
if (response.status === 204) return void 0;
|
|
48
|
+
return unwrap(await response.json());
|
|
49
|
+
};
|
|
50
|
+
var ServiceClient = class {
|
|
51
|
+
#host;
|
|
52
|
+
constructor(host) {
|
|
53
|
+
this.#host = host;
|
|
54
|
+
}
|
|
55
|
+
call(endpoint, options) {
|
|
56
|
+
return call(this.#host, endpoint, options);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const ServiceKeyRoute = (header, expected) => (req) => {
|
|
60
|
+
const presented = req.headers[header];
|
|
61
|
+
if (typeof presented !== "string" || presented === "") throw AuthError.Unauthorized();
|
|
62
|
+
const left = Buffer.from(presented);
|
|
63
|
+
const right = Buffer.from(expected);
|
|
64
|
+
if (left.length !== right.length || !timingSafeEqual(left, right)) throw AuthError.Unauthorized();
|
|
65
|
+
};
|
|
66
|
+
export { CallError, ServiceClient, ServiceKeyRoute, call, interpolate, isNotFound, request };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { RateLimitOptions as RateLimitOptions$1 } from "@fastify/rate-limit";
|
|
2
|
+
import { FastifyReply, FastifyRequest } from "fastify";
|
|
3
|
+
export type MiddlewareFn = (req: FastifyRequest, reply: FastifyReply) => void | Promise<void>;
|
|
4
|
+
export interface MiddlewareBinding {
|
|
5
|
+
handlerName: string | symbol | null;
|
|
6
|
+
middleware: MiddlewareFn;
|
|
7
|
+
}
|
|
8
|
+
export interface RateLimitOptions {
|
|
9
|
+
max: number;
|
|
10
|
+
window: RateLimitWindow;
|
|
11
|
+
}
|
|
12
|
+
export interface RateLimitBinding {
|
|
13
|
+
handlerName: string | symbol;
|
|
14
|
+
limit: RateLimitOptions$1;
|
|
15
|
+
}
|
|
16
|
+
export type RateLimitWindow = `${number}${'s' | 'm' | 'h'}`;
|
|
17
|
+
export declare const Middleware: (...middleware: MiddlewareFn[]) => ClassDecorator & MethodDecorator;
|
|
18
|
+
export declare const getMiddleware: (ctor: object, handlerName: string | symbol) => MiddlewareFn[];
|
|
19
|
+
export declare const getClassMiddleware: (ctor: object) => MiddlewareFn[];
|
|
20
|
+
export declare const RateLimit: ({ max, window }: RateLimitOptions) => MethodDecorator;
|
|
21
|
+
export declare const getRateLimit: (ctor: object, handlerName: string | symbol) => RateLimitOptions$1 | undefined;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ClassMetadata } from "../app/metadata.js";
|
|
2
|
+
// lib/http/middleware.ts
|
|
3
|
+
const bindingsByController = new ClassMetadata();
|
|
4
|
+
const limitsByHandler = new ClassMetadata();
|
|
5
|
+
const bindingsOf = (ctor) => {
|
|
6
|
+
const parent = Object.getPrototypeOf(ctor);
|
|
7
|
+
if (typeof parent !== "function" || parent === Function.prototype) return bindingsByController.get(ctor);
|
|
8
|
+
return [...bindingsOf(parent), ...bindingsByController.get(ctor)];
|
|
9
|
+
};
|
|
10
|
+
const Middleware = (...middleware) => {
|
|
11
|
+
return (target, handlerName) => {
|
|
12
|
+
const ctor = handlerName === void 0 ? target : target.constructor;
|
|
13
|
+
for (const fn of middleware) bindingsByController.append(ctor, {
|
|
14
|
+
handlerName: handlerName ?? null,
|
|
15
|
+
middleware: fn
|
|
16
|
+
});
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
const getMiddleware = (ctor, handlerName) => {
|
|
20
|
+
return bindingsOf(ctor).filter((binding) => binding.handlerName === null || binding.handlerName === handlerName).sort((a, b) => Number(a.handlerName !== null) - Number(b.handlerName !== null)).map((binding) => binding.middleware);
|
|
21
|
+
};
|
|
22
|
+
const getClassMiddleware = (ctor) => {
|
|
23
|
+
return bindingsOf(ctor).filter((binding) => binding.handlerName === null).map((binding) => binding.middleware);
|
|
24
|
+
};
|
|
25
|
+
const RateLimit = ({ max, window }) => {
|
|
26
|
+
return (target, handlerName) => {
|
|
27
|
+
limitsByHandler.append(target.constructor, {
|
|
28
|
+
handlerName,
|
|
29
|
+
limit: {
|
|
30
|
+
max,
|
|
31
|
+
timeWindow: window
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const getRateLimit = (ctor, handlerName) => {
|
|
37
|
+
return limitsByHandler.get(ctor).find((binding) => binding.handlerName === handlerName)?.limit;
|
|
38
|
+
};
|
|
39
|
+
export { Middleware, RateLimit, getClassMiddleware, getMiddleware, getRateLimit };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// lib/http/org-context.ts
|
|
2
|
+
const createOrgContext = (load, ttlMs) => {
|
|
3
|
+
const byUser = /* @__PURE__ */ new Map();
|
|
4
|
+
return {
|
|
5
|
+
forget: (userId) => {
|
|
6
|
+
byUser.delete(userId);
|
|
7
|
+
},
|
|
8
|
+
forgetAll: () => {
|
|
9
|
+
byUser.clear();
|
|
10
|
+
},
|
|
11
|
+
of: async (userId) => {
|
|
12
|
+
const cached = byUser.get(userId);
|
|
13
|
+
if (cached !== void 0 && cached.expiresAt > Date.now()) return cached.orgId;
|
|
14
|
+
const orgId = await load(userId);
|
|
15
|
+
byUser.set(userId, {
|
|
16
|
+
orgId,
|
|
17
|
+
expiresAt: Date.now() + ttlMs
|
|
18
|
+
});
|
|
19
|
+
return orgId;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
export { createOrgContext };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ClassMetadata } from "../app/metadata.js";
|
|
2
|
+
import { FastifyReply, FastifyRequest } from "fastify";
|
|
3
|
+
import { IValidation } from "typia";
|
|
4
|
+
export interface UploadedFile {
|
|
5
|
+
filename: string;
|
|
6
|
+
buffer: Buffer;
|
|
7
|
+
}
|
|
8
|
+
export type ParamResolver = (req: FastifyRequest, reply?: FastifyReply) => unknown;
|
|
9
|
+
export type BodyValidator<T> = (input: unknown) => IValidation<T>;
|
|
10
|
+
export interface ParamBinding {
|
|
11
|
+
handlerName: string | symbol;
|
|
12
|
+
index: number;
|
|
13
|
+
resolve: ParamResolver;
|
|
14
|
+
}
|
|
15
|
+
export interface PaginationOptions {
|
|
16
|
+
defaultLimit?: number;
|
|
17
|
+
maxLimit?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface Page {
|
|
20
|
+
limit: number;
|
|
21
|
+
offset: number;
|
|
22
|
+
}
|
|
23
|
+
export declare const bindingsByController: ClassMetadata<ParamBinding>;
|
|
24
|
+
export declare const createParamDecorator: (resolve: ParamResolver) => ParameterDecorator;
|
|
25
|
+
export declare const getParamResolvers: (ctor: object, handlerName: string | symbol) => ParamResolver[];
|
|
26
|
+
export declare const parseId: (raw: unknown) => string;
|
|
27
|
+
export declare const parseOrdinal: (raw: unknown) => number;
|
|
28
|
+
export declare const parsePagination: (query: unknown, options?: PaginationOptions) => Page;
|
|
29
|
+
export declare const parseBody: <T>(validate: BodyValidator<T>, body: unknown) => T;
|
|
30
|
+
export declare const Body: <T>(validate?: BodyValidator<T>) => ParameterDecorator;
|
|
31
|
+
export declare const IdParam: (name: string) => ParameterDecorator;
|
|
32
|
+
export declare const OrdinalParam: (name: string) => ParameterDecorator;
|
|
33
|
+
export declare const Req: () => ParameterDecorator;
|
|
34
|
+
export declare const Reply: () => ParameterDecorator;
|
|
35
|
+
export declare const Param: (name: string) => ParameterDecorator;
|
|
36
|
+
export declare const Query: (name?: string) => ParameterDecorator;
|
|
37
|
+
export declare const IdQuery: (name: string) => ParameterDecorator;
|
|
38
|
+
export declare const OptionalIdQuery: (name: string) => ParameterDecorator;
|
|
39
|
+
export declare const Pagination: (options?: PaginationOptions) => ParameterDecorator;
|
|
40
|
+
export declare const UploadedFile: () => ParameterDecorator;
|