@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,8 @@
|
|
|
1
|
+
// \0@oxc-project+runtime@0.156.0/helpers/esm/decorate.js
|
|
2
|
+
function __decorate(decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
}
|
|
8
|
+
export { __decorate as default };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Discovered } from "./discovery.js";
|
|
2
|
+
import { FastifyInstance } from "fastify";
|
|
3
|
+
import { DataSource } from "typeorm";
|
|
4
|
+
export interface BuildOptions {
|
|
5
|
+
queues?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface ApplicationLog {
|
|
8
|
+
level: string;
|
|
9
|
+
pretty: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface ApplicationOptions {
|
|
12
|
+
port: number;
|
|
13
|
+
corsOrigins: string[];
|
|
14
|
+
publicPaths?: string[];
|
|
15
|
+
log: ApplicationLog;
|
|
16
|
+
discover: () => Promise<Discovered>;
|
|
17
|
+
createDataSource?: (entities: Function[]) => DataSource;
|
|
18
|
+
plugins?: (app: FastifyInstance) => Promise<void>;
|
|
19
|
+
afterDatabase?: (dataSource: DataSource) => Promise<void>;
|
|
20
|
+
afterMount?: (discovered: Discovered) => void;
|
|
21
|
+
}
|
|
22
|
+
export interface ListenTarget {
|
|
23
|
+
start(): Promise<void>;
|
|
24
|
+
stop(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export default class Application {
|
|
27
|
+
#private;
|
|
28
|
+
constructor(options: ApplicationOptions);
|
|
29
|
+
get dataSource(): DataSource | undefined;
|
|
30
|
+
build({ queues: startQueues }?: BuildOptions): Promise<FastifyInstance>;
|
|
31
|
+
start(): Promise<void>;
|
|
32
|
+
stop(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
export declare const listen: (app: ListenTarget, failed?: string) => void;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { RateLimitError, RuntimeError, ServerError, ValidationError } from "./errors.js";
|
|
2
|
+
import { logger } from "./logger.js";
|
|
3
|
+
import { broadcast } from "../events/Broadcast.js";
|
|
4
|
+
import { registerCompression } from "./compression.js";
|
|
5
|
+
import { eventBus, registerEventGroup } from "../events/EventBus.js";
|
|
6
|
+
import { redis } from "./redis.js";
|
|
7
|
+
import cors from "@fastify/cors";
|
|
8
|
+
import rateLimit from "@fastify/rate-limit";
|
|
9
|
+
import Fastify, { LogController } from "fastify";
|
|
10
|
+
// lib/app/Application.ts
|
|
11
|
+
var Application = class {
|
|
12
|
+
#app;
|
|
13
|
+
#dataSource;
|
|
14
|
+
#queues = [];
|
|
15
|
+
#options;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.#options = options;
|
|
18
|
+
}
|
|
19
|
+
get dataSource() {
|
|
20
|
+
return this.#dataSource;
|
|
21
|
+
}
|
|
22
|
+
async build({ queues: startQueues = true } = {}) {
|
|
23
|
+
logger.configure({
|
|
24
|
+
level: this.#options.log.level,
|
|
25
|
+
pretty: this.#options.log.pretty
|
|
26
|
+
});
|
|
27
|
+
this.#app = Fastify({
|
|
28
|
+
loggerInstance: logger.raw,
|
|
29
|
+
logController: new LogController({ disableRequestLogging: true }),
|
|
30
|
+
trustProxy: [
|
|
31
|
+
"loopback",
|
|
32
|
+
"linklocal",
|
|
33
|
+
"uniquelocal"
|
|
34
|
+
]
|
|
35
|
+
});
|
|
36
|
+
await this.#app.register(cors, { delegator: (req, resolve) => {
|
|
37
|
+
const open = this.#options.publicPaths?.some((path) => req.url.startsWith(path)) ?? false;
|
|
38
|
+
resolve(null, {
|
|
39
|
+
origin: open ? true : this.#options.corsOrigins,
|
|
40
|
+
credentials: !open,
|
|
41
|
+
methods: [
|
|
42
|
+
"GET",
|
|
43
|
+
"HEAD",
|
|
44
|
+
"POST",
|
|
45
|
+
"PUT",
|
|
46
|
+
"PATCH",
|
|
47
|
+
"DELETE"
|
|
48
|
+
]
|
|
49
|
+
});
|
|
50
|
+
} });
|
|
51
|
+
await this.#app.register(rateLimit, {
|
|
52
|
+
global: false,
|
|
53
|
+
redis,
|
|
54
|
+
nameSpace: "rl:",
|
|
55
|
+
errorResponseBuilder: () => RateLimitError.TooManyRequests()
|
|
56
|
+
});
|
|
57
|
+
registerCompression(this.#app);
|
|
58
|
+
if (this.#options.plugins) await this.#options.plugins(this.#app);
|
|
59
|
+
const discovered = await this.#options.discover();
|
|
60
|
+
await this.#openDatabase(discovered.entities);
|
|
61
|
+
this.#registerErrorHandler();
|
|
62
|
+
this.#registerRequestLogging();
|
|
63
|
+
await this.#mountControllers(discovered.controllers);
|
|
64
|
+
this.#app.get("/health", async () => ({ status: "ok" }));
|
|
65
|
+
this.#mountGateways(discovered.gateways);
|
|
66
|
+
discovered.events.forEach(registerEventGroup);
|
|
67
|
+
this.#options.afterMount?.(discovered);
|
|
68
|
+
if (startQueues) this.#startQueues(discovered.queues);
|
|
69
|
+
return this.#app;
|
|
70
|
+
}
|
|
71
|
+
async start() {
|
|
72
|
+
await this.build();
|
|
73
|
+
await this.#app.listen({
|
|
74
|
+
port: this.#options.port,
|
|
75
|
+
host: "0.0.0.0"
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async stop() {
|
|
79
|
+
await this.#app.close();
|
|
80
|
+
await Promise.all(this.#queues.map((queue) => queue.close()));
|
|
81
|
+
await eventBus.close();
|
|
82
|
+
await broadcast.close();
|
|
83
|
+
await this.#dataSource?.destroy();
|
|
84
|
+
}
|
|
85
|
+
async #openDatabase(entities) {
|
|
86
|
+
if (!this.#options.createDataSource) return;
|
|
87
|
+
this.#dataSource = this.#options.createDataSource(entities);
|
|
88
|
+
await this.#dataSource.initialize();
|
|
89
|
+
if (this.#options.afterDatabase) await this.#options.afterDatabase(this.#dataSource);
|
|
90
|
+
}
|
|
91
|
+
#registerErrorHandler() {
|
|
92
|
+
this.#app.setErrorHandler((err, req, reply) => {
|
|
93
|
+
const answer = err instanceof RuntimeError ? err : ServerError.Internal();
|
|
94
|
+
if (answer.statusCode >= 500) logger.error(`${req.method} ${req.url}`, err, {
|
|
95
|
+
scope: "http",
|
|
96
|
+
statusCode: answer.statusCode
|
|
97
|
+
});
|
|
98
|
+
const payload = { error: answer.message };
|
|
99
|
+
if (err instanceof ValidationError) payload.errors = err.errors;
|
|
100
|
+
reply.status(answer.statusCode).send(payload);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
#registerRequestLogging() {
|
|
104
|
+
this.#app.addHook("onResponse", (req, reply, done) => {
|
|
105
|
+
logger.debug(`${req.method} ${req.url}`, {
|
|
106
|
+
scope: "http",
|
|
107
|
+
statusCode: reply.statusCode,
|
|
108
|
+
ms: Math.round(reply.elapsedTime)
|
|
109
|
+
});
|
|
110
|
+
done();
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
async #mountControllers(controllers) {
|
|
114
|
+
for (const { prefix, Controller } of controllers) await new Controller().register(this.#app, prefix);
|
|
115
|
+
}
|
|
116
|
+
#mountGateways(gateways) {
|
|
117
|
+
for (const Gateway of gateways) new Gateway().register(this.#app);
|
|
118
|
+
}
|
|
119
|
+
#startQueues(queues) {
|
|
120
|
+
for (const Queue of queues) {
|
|
121
|
+
const queue = new Queue();
|
|
122
|
+
queue.startWorker();
|
|
123
|
+
this.#queues.push(queue);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const listen = (app, failed = "Failed to start server") => {
|
|
128
|
+
app.start().catch((err) => {
|
|
129
|
+
logger.error(failed, err);
|
|
130
|
+
process.exit(1);
|
|
131
|
+
});
|
|
132
|
+
for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => {
|
|
133
|
+
app.stop().finally(() => process.exit(0));
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
export { Application as default, listen };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
// lib/app/abort.ts
|
|
3
|
+
var AbortScope = class {
|
|
4
|
+
#storage = new AsyncLocalStorage();
|
|
5
|
+
run(signal, work) {
|
|
6
|
+
return this.#storage.run(signal, work);
|
|
7
|
+
}
|
|
8
|
+
detached(work) {
|
|
9
|
+
return this.#storage.exit(work);
|
|
10
|
+
}
|
|
11
|
+
signal() {
|
|
12
|
+
return this.#storage.getStore();
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const abortScope = new AbortScope();
|
|
16
|
+
export { abortScope };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { promisify } from "node:util";
|
|
2
|
+
import { brotliCompress, constants, gzip } from "node:zlib";
|
|
3
|
+
// lib/app/compression.ts
|
|
4
|
+
const encodingFor = (accepted) => {
|
|
5
|
+
const offered = (accepted ?? "").split(",").map((part) => part.trim().split(";")[0]);
|
|
6
|
+
if (offered.includes("br")) return "br";
|
|
7
|
+
return offered.includes("gzip") ? "gzip" : null;
|
|
8
|
+
};
|
|
9
|
+
const isCompressible = (reply) => {
|
|
10
|
+
return !reply.hasHeader("content-encoding") && /^(application\/(json|xml|javascript)|text\/|image\/svg\+xml)/.test(String(reply.getHeader("content-type") ?? ""));
|
|
11
|
+
};
|
|
12
|
+
const varyOnEncoding = (reply) => {
|
|
13
|
+
const vary = reply.getHeader("vary");
|
|
14
|
+
reply.header("vary", vary === void 0 ? "Accept-Encoding" : `${String(vary)}, Accept-Encoding`);
|
|
15
|
+
};
|
|
16
|
+
const registerCompression = (app) => {
|
|
17
|
+
const brotli = promisify(brotliCompress);
|
|
18
|
+
const gzipped = promisify(gzip);
|
|
19
|
+
app.addHook("onSend", async (request, reply, payload) => {
|
|
20
|
+
if (typeof payload !== "string" && !Buffer.isBuffer(payload)) return payload;
|
|
21
|
+
if (!isCompressible(reply)) return payload;
|
|
22
|
+
const body = Buffer.from(payload);
|
|
23
|
+
const encoding = encodingFor(request.headers["accept-encoding"]);
|
|
24
|
+
if (body.length < 1024 || encoding === null) return payload;
|
|
25
|
+
const compressed = encoding === "br" ? await brotli(body, { params: {
|
|
26
|
+
[constants.BROTLI_PARAM_QUALITY]: 4,
|
|
27
|
+
[constants.BROTLI_PARAM_SIZE_HINT]: body.length
|
|
28
|
+
} }) : await gzipped(body);
|
|
29
|
+
reply.header("content-encoding", encoding);
|
|
30
|
+
reply.removeHeader("content-length");
|
|
31
|
+
varyOnEncoding(reply);
|
|
32
|
+
return compressed;
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
export { registerCompression };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export interface ReadableRedisConfig {
|
|
2
|
+
host: string;
|
|
3
|
+
port: number;
|
|
4
|
+
}
|
|
5
|
+
export interface ReadableStorageConfig {
|
|
6
|
+
endpoint: string;
|
|
7
|
+
region: string;
|
|
8
|
+
accessKey: string;
|
|
9
|
+
secretKey: string;
|
|
10
|
+
bucket: string;
|
|
11
|
+
publicUrl: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ReadableDatabaseConfig {
|
|
14
|
+
url: string;
|
|
15
|
+
schema: string | undefined;
|
|
16
|
+
synchronize: boolean;
|
|
17
|
+
timestamptz?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface ReadableConfig {
|
|
20
|
+
name: string;
|
|
21
|
+
jwtSecret: string | null;
|
|
22
|
+
redis: ReadableRedisConfig;
|
|
23
|
+
storage: ReadableStorageConfig | null;
|
|
24
|
+
}
|
|
25
|
+
export declare const requiredEnv: (key: string) => string;
|
|
26
|
+
export declare const optionalEnv: (key: string) => string | undefined;
|
|
27
|
+
export declare const configure: (next: ReadableConfig) => void;
|
|
28
|
+
export declare const readableConfig: () => ReadableConfig;
|
|
29
|
+
export declare const jwtSecret: () => string;
|
|
30
|
+
export declare const storageConfig: () => ReadableStorageConfig;
|
|
31
|
+
export declare const serviceConfig: (corsFallback: string) => {
|
|
32
|
+
port: number;
|
|
33
|
+
corsOrigins: string[];
|
|
34
|
+
database: {
|
|
35
|
+
url: string;
|
|
36
|
+
schema: string | undefined;
|
|
37
|
+
synchronize: boolean;
|
|
38
|
+
};
|
|
39
|
+
log: {
|
|
40
|
+
level: string;
|
|
41
|
+
pretty: boolean;
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
export declare const redisFromEnv: () => ReadableRedisConfig;
|
|
45
|
+
export declare const storageFromEnv: () => ReadableStorageConfig;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ConfigError } from "./errors.js";
|
|
2
|
+
// lib/app/config.ts
|
|
3
|
+
let current;
|
|
4
|
+
const requiredEnv = (key) => {
|
|
5
|
+
const value = process.env[key];
|
|
6
|
+
if (value === void 0 || value === "") throw ConfigError.MissingEnv(key);
|
|
7
|
+
return value;
|
|
8
|
+
};
|
|
9
|
+
const optionalEnv = (key) => {
|
|
10
|
+
const value = process.env[key];
|
|
11
|
+
return value === void 0 || value === "" ? void 0 : value;
|
|
12
|
+
};
|
|
13
|
+
const configure = (next) => {
|
|
14
|
+
current = next;
|
|
15
|
+
};
|
|
16
|
+
const readableConfig = () => {
|
|
17
|
+
if (!current) throw ConfigError.MissingEnv("readable");
|
|
18
|
+
return current;
|
|
19
|
+
};
|
|
20
|
+
const jwtSecret = () => {
|
|
21
|
+
const secret = readableConfig().jwtSecret;
|
|
22
|
+
if (secret === null) throw ConfigError.MissingEnv("JWT_SECRET");
|
|
23
|
+
return secret;
|
|
24
|
+
};
|
|
25
|
+
const storageConfig = () => {
|
|
26
|
+
const storage = readableConfig().storage;
|
|
27
|
+
if (storage === null) throw ConfigError.MissingEnv("STORAGE");
|
|
28
|
+
return storage;
|
|
29
|
+
};
|
|
30
|
+
const serviceConfig = (corsFallback) => ({
|
|
31
|
+
port: Number(requiredEnv("PORT")),
|
|
32
|
+
corsOrigins: (optionalEnv("CORS_ORIGIN") ?? corsFallback).split(",").map((origin) => origin.trim()).filter((origin) => origin !== ""),
|
|
33
|
+
database: {
|
|
34
|
+
url: requiredEnv("DATABASE_URL"),
|
|
35
|
+
schema: optionalEnv("DATABASE_SCHEMA"),
|
|
36
|
+
synchronize: optionalEnv("DATABASE_SYNCHRONIZE") !== "false"
|
|
37
|
+
},
|
|
38
|
+
log: {
|
|
39
|
+
level: optionalEnv("LOG_LEVEL") ?? "info",
|
|
40
|
+
pretty: optionalEnv("LOG_PRETTY") === "true"
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
const redisFromEnv = () => ({
|
|
44
|
+
host: requiredEnv("REDIS_HOST"),
|
|
45
|
+
port: Number(requiredEnv("REDIS_PORT"))
|
|
46
|
+
});
|
|
47
|
+
const storageFromEnv = () => ({
|
|
48
|
+
endpoint: requiredEnv("STORAGE_ENDPOINT"),
|
|
49
|
+
region: optionalEnv("STORAGE_REGION") ?? "us-east-1",
|
|
50
|
+
accessKey: requiredEnv("STORAGE_ACCESS_KEY"),
|
|
51
|
+
secretKey: requiredEnv("STORAGE_SECRET_KEY"),
|
|
52
|
+
bucket: requiredEnv("STORAGE_BUCKET"),
|
|
53
|
+
publicUrl: requiredEnv("STORAGE_PUBLIC_URL")
|
|
54
|
+
});
|
|
55
|
+
export { configure, jwtSecret, optionalEnv, readableConfig, redisFromEnv, requiredEnv, serviceConfig, storageConfig, storageFromEnv };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import BaseGateway from "../gateway/Gateway.js";
|
|
2
|
+
import BaseQueue from "../queues/BaseQueue.js";
|
|
3
|
+
import BaseController from "../http/Controller.js";
|
|
4
|
+
export interface MountedController {
|
|
5
|
+
prefix: string;
|
|
6
|
+
Controller: new () => BaseController;
|
|
7
|
+
}
|
|
8
|
+
export interface Discovered {
|
|
9
|
+
controllers: MountedController[];
|
|
10
|
+
entities: Function[];
|
|
11
|
+
events: Array<new () => object>;
|
|
12
|
+
queues: Array<new () => BaseQueue<unknown>>;
|
|
13
|
+
gateways: Array<new () => BaseGateway>;
|
|
14
|
+
tools: Array<new () => object>;
|
|
15
|
+
}
|
|
16
|
+
export type ModuleLoader = (url: string) => Promise<{
|
|
17
|
+
default?: unknown;
|
|
18
|
+
}>;
|
|
19
|
+
export declare class ModuleDiscovery {
|
|
20
|
+
#private;
|
|
21
|
+
private readonly modulesDir;
|
|
22
|
+
private readonly load;
|
|
23
|
+
constructor(modulesDir: string, load: ModuleLoader);
|
|
24
|
+
discover(): Promise<Discovered>;
|
|
25
|
+
static merge(parts: Discovered[]): Discovered;
|
|
26
|
+
}
|
|
27
|
+
export declare const discoverFrom: (metaUrl: string, load: ModuleLoader, folders?: string[]) => Promise<Discovered>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { getControllerPrefix } from "../http/Controller.js";
|
|
2
|
+
import { readdir } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
+
// lib/app/discovery.ts
|
|
6
|
+
var ModuleDiscovery = class {
|
|
7
|
+
constructor(modulesDir, load) {
|
|
8
|
+
this.modulesDir = modulesDir;
|
|
9
|
+
this.load = load;
|
|
10
|
+
}
|
|
11
|
+
async discover() {
|
|
12
|
+
const names = (await readdir(this.modulesDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
13
|
+
const discovered = {
|
|
14
|
+
controllers: [],
|
|
15
|
+
entities: [],
|
|
16
|
+
events: [],
|
|
17
|
+
queues: [],
|
|
18
|
+
gateways: [],
|
|
19
|
+
tools: []
|
|
20
|
+
};
|
|
21
|
+
for (const name of names) {
|
|
22
|
+
const controllers = await this.#loadDefaults(name, "controllers");
|
|
23
|
+
discovered.controllers.push(...controllers.map((Controller) => ({
|
|
24
|
+
prefix: getControllerPrefix(Controller) ?? `/${name}`,
|
|
25
|
+
Controller
|
|
26
|
+
})));
|
|
27
|
+
discovered.entities.push(...await this.#loadDefaults(name, "models"));
|
|
28
|
+
discovered.events.push(...await this.#loadDefaults(name, "events"));
|
|
29
|
+
discovered.queues.push(...await this.#loadDefaults(name, "queues"));
|
|
30
|
+
discovered.gateways.push(...await this.#loadDefaults(name, "gateways"));
|
|
31
|
+
discovered.tools.push(...await this.#loadDefaults(name, "tools"));
|
|
32
|
+
}
|
|
33
|
+
return discovered;
|
|
34
|
+
}
|
|
35
|
+
static merge(parts) {
|
|
36
|
+
const discovered = {
|
|
37
|
+
controllers: [],
|
|
38
|
+
entities: [],
|
|
39
|
+
events: [],
|
|
40
|
+
queues: [],
|
|
41
|
+
gateways: [],
|
|
42
|
+
tools: []
|
|
43
|
+
};
|
|
44
|
+
for (const part of parts) {
|
|
45
|
+
discovered.controllers.push(...part.controllers);
|
|
46
|
+
discovered.entities.push(...part.entities);
|
|
47
|
+
discovered.events.push(...part.events);
|
|
48
|
+
discovered.queues.push(...part.queues);
|
|
49
|
+
discovered.gateways.push(...part.gateways);
|
|
50
|
+
discovered.tools.push(...part.tools);
|
|
51
|
+
}
|
|
52
|
+
return discovered;
|
|
53
|
+
}
|
|
54
|
+
async #loadDefaults(moduleName, category) {
|
|
55
|
+
const dir = join(this.modulesDir, moduleName, category);
|
|
56
|
+
let files;
|
|
57
|
+
try {
|
|
58
|
+
files = await readdir(dir);
|
|
59
|
+
} catch {
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
const loaded = [];
|
|
63
|
+
for (const file of files.sort()) {
|
|
64
|
+
if (!file.endsWith(".ts") || file.endsWith(".d.ts")) continue;
|
|
65
|
+
const imported = await this.load(pathToFileURL(join(dir, file)).href);
|
|
66
|
+
if (imported.default) loaded.push(imported.default);
|
|
67
|
+
}
|
|
68
|
+
return loaded;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
const discoverFrom = async (metaUrl, load, folders = ["modules"]) => {
|
|
72
|
+
const srcDir = join(dirname(fileURLToPath(metaUrl)), "..");
|
|
73
|
+
return ModuleDiscovery.merge(await Promise.all(folders.map((folder) => new ModuleDiscovery(join(srcDir, folder), load).discover())));
|
|
74
|
+
};
|
|
75
|
+
export { ModuleDiscovery, discoverFrom };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ErrorTable } from "@pollium/readable-contracts/errors";
|
|
2
|
+
type ErrorFactory = (detail?: string) => RuntimeError;
|
|
3
|
+
export declare class RuntimeError extends Error {
|
|
4
|
+
statusCode: number;
|
|
5
|
+
constructor(message: string, statusCode: number);
|
|
6
|
+
}
|
|
7
|
+
export declare class ValidationError extends RuntimeError {
|
|
8
|
+
readonly errors: Record<string, string>;
|
|
9
|
+
constructor(errors: Record<string, string>, template?: RuntimeError);
|
|
10
|
+
}
|
|
11
|
+
export declare const defineErrors: <T extends ErrorTable>({ domain, causes }: T) => Record<keyof T["causes"], ErrorFactory>;
|
|
12
|
+
export declare const RequestError: Record<"InvalidId" | "InvalidPagination" | "FileMissing" | "FileTooLarge" | "ValidationFailed", ErrorFactory>;
|
|
13
|
+
export declare const ServerError: Record<"Internal", ErrorFactory>;
|
|
14
|
+
export declare const AuthError: Record<"Unauthorized" | "InvalidToken", ErrorFactory>;
|
|
15
|
+
export declare const GatewayError: Record<"Internal" | "MissingChannel" | "MalformedFrame" | "UnknownMessageType", ErrorFactory>;
|
|
16
|
+
export declare const RateLimitError: Record<"TooManyRequests", ErrorFactory>;
|
|
17
|
+
export declare const RouteError: Record<"PrefixMismatch", ErrorFactory>;
|
|
18
|
+
export declare const EventError: Record<"UndefinedGroup", ErrorFactory>;
|
|
19
|
+
export declare const ConfigError: Record<"MissingEnv" | "InvalidEnv" | "InvalidEncryptionKey", ErrorFactory>;
|
|
20
|
+
export declare const CryptoError: Record<"EncryptFailed" | "DecryptFailed", ErrorFactory>;
|
|
21
|
+
export declare const SchemaError: Record<"PendingMigrations" | "Irreversible", ErrorFactory>;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { AuthErrors, GatewayErrors, RateLimitErrors, RequestErrors, ServerErrors } from "@pollium/readable-contracts/errors";
|
|
2
|
+
// lib/app/errors.ts
|
|
3
|
+
var RuntimeError = class extends Error {
|
|
4
|
+
constructor(message, statusCode) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.statusCode = statusCode;
|
|
7
|
+
Error.captureStackTrace(this, this.constructor);
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var ValidationError = class extends RuntimeError {
|
|
11
|
+
constructor(errors, template = RequestError.ValidationFailed()) {
|
|
12
|
+
super(template.message, template.statusCode);
|
|
13
|
+
this.errors = errors;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
const defineErrors = ({ domain, causes }) => {
|
|
17
|
+
const factories = {};
|
|
18
|
+
for (const [cause, status] of Object.entries(causes)) factories[cause] = (detail) => {
|
|
19
|
+
return new RuntimeError(detail === void 0 ? `${domain}::${cause}` : `${domain}::${cause}:${detail}`, status);
|
|
20
|
+
};
|
|
21
|
+
return factories;
|
|
22
|
+
};
|
|
23
|
+
const RequestError = defineErrors(RequestErrors);
|
|
24
|
+
const ServerError = defineErrors(ServerErrors);
|
|
25
|
+
const AuthError = defineErrors(AuthErrors);
|
|
26
|
+
const GatewayError = defineErrors(GatewayErrors);
|
|
27
|
+
const RateLimitError = defineErrors(RateLimitErrors);
|
|
28
|
+
const RouteError = defineErrors({
|
|
29
|
+
domain: "Route",
|
|
30
|
+
causes: { PrefixMismatch: 500 }
|
|
31
|
+
});
|
|
32
|
+
const EventError = defineErrors({
|
|
33
|
+
domain: "Events",
|
|
34
|
+
causes: { UndefinedGroup: 500 }
|
|
35
|
+
});
|
|
36
|
+
const ConfigError = defineErrors({
|
|
37
|
+
domain: "Config",
|
|
38
|
+
causes: {
|
|
39
|
+
MissingEnv: 500,
|
|
40
|
+
InvalidEnv: 500,
|
|
41
|
+
InvalidEncryptionKey: 500
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
const CryptoError = defineErrors({
|
|
45
|
+
domain: "Crypto",
|
|
46
|
+
causes: {
|
|
47
|
+
EncryptFailed: 400,
|
|
48
|
+
DecryptFailed: 500
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
const SchemaError = defineErrors({
|
|
52
|
+
domain: "Schema",
|
|
53
|
+
causes: {
|
|
54
|
+
PendingMigrations: 500,
|
|
55
|
+
Irreversible: 500
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
export { AuthError, ConfigError, CryptoError, EventError, GatewayError, RateLimitError, RequestError, RouteError, RuntimeError, SchemaError, ServerError, ValidationError, defineErrors };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Logger as Logger$1 } from "pino";
|
|
2
|
+
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
3
|
+
export type LogMethod = 'debug' | 'info' | 'warn';
|
|
4
|
+
export type LogContext = Record<string, unknown>;
|
|
5
|
+
export interface LoggerOptions {
|
|
6
|
+
level: LogLevel;
|
|
7
|
+
pretty: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare class Logger {
|
|
10
|
+
#private;
|
|
11
|
+
constructor(instance?: Logger$1);
|
|
12
|
+
configure(options: LoggerOptions): void;
|
|
13
|
+
child(bindings: LogContext): Logger;
|
|
14
|
+
debug(message: string, context?: LogContext): void;
|
|
15
|
+
info(message: string, context?: LogContext): void;
|
|
16
|
+
warn(message: string, context?: LogContext): void;
|
|
17
|
+
error(message: string, error?: unknown, context?: LogContext): void;
|
|
18
|
+
get raw(): Logger$1;
|
|
19
|
+
}
|
|
20
|
+
export declare const logger: Logger;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import pino from "pino";
|
|
2
|
+
// lib/app/logger.ts
|
|
3
|
+
var Logger = class Logger {
|
|
4
|
+
#pino;
|
|
5
|
+
constructor(instance) {
|
|
6
|
+
this.#pino = instance ?? pino({ level: "info" });
|
|
7
|
+
}
|
|
8
|
+
configure(options) {
|
|
9
|
+
this.#pino = pino({
|
|
10
|
+
level: options.level,
|
|
11
|
+
transport: options.pretty ? { target: "pino-pretty" } : void 0
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
child(bindings) {
|
|
15
|
+
return new Logger(this.#pino.child(bindings));
|
|
16
|
+
}
|
|
17
|
+
#log(level, message, context) {
|
|
18
|
+
this.#pino[level](context ?? {}, message);
|
|
19
|
+
}
|
|
20
|
+
debug(message, context) {
|
|
21
|
+
this.#log("debug", message, context);
|
|
22
|
+
}
|
|
23
|
+
info(message, context) {
|
|
24
|
+
this.#log("info", message, context);
|
|
25
|
+
}
|
|
26
|
+
warn(message, context) {
|
|
27
|
+
this.#log("warn", message, context);
|
|
28
|
+
}
|
|
29
|
+
error(message, error, context) {
|
|
30
|
+
this.#pino.error({
|
|
31
|
+
...context,
|
|
32
|
+
err: error
|
|
33
|
+
}, message);
|
|
34
|
+
}
|
|
35
|
+
get raw() {
|
|
36
|
+
return this.#pino;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const logger = new Logger();
|
|
40
|
+
export { Logger, logger };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// lib/app/metadata.ts
|
|
2
|
+
var ClassMetadata = class {
|
|
3
|
+
#store = /* @__PURE__ */ new WeakMap();
|
|
4
|
+
append(ctor, item) {
|
|
5
|
+
let items = this.#store.get(ctor);
|
|
6
|
+
if (!items) {
|
|
7
|
+
items = [];
|
|
8
|
+
this.#store.set(ctor, items);
|
|
9
|
+
}
|
|
10
|
+
items.push(item);
|
|
11
|
+
}
|
|
12
|
+
get(ctor) {
|
|
13
|
+
return this.#store.get(ctor) ?? [];
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
export { ClassMetadata };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readableConfig } from "./config.js";
|
|
2
|
+
import { Redis } from "ioredis";
|
|
3
|
+
// lib/app/redis.ts
|
|
4
|
+
let client;
|
|
5
|
+
const redisOptions = () => {
|
|
6
|
+
const { host, port } = readableConfig().redis;
|
|
7
|
+
return {
|
|
8
|
+
host,
|
|
9
|
+
port
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
const createRedis = (options = {}) => new Redis({
|
|
13
|
+
...redisOptions(),
|
|
14
|
+
...options
|
|
15
|
+
});
|
|
16
|
+
const connect = () => {
|
|
17
|
+
client ??= createRedis({ lazyConnect: true });
|
|
18
|
+
return client;
|
|
19
|
+
};
|
|
20
|
+
const redis = new Proxy({}, { get(_target, prop) {
|
|
21
|
+
const value = Reflect.get(connect(), prop);
|
|
22
|
+
return typeof value === "function" ? value.bind(connect()) : value;
|
|
23
|
+
} });
|
|
24
|
+
export { createRedis, redis, redisOptions };
|