@pollium/readable 0.0.0-stage → 0.1.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.
Files changed (72) hide show
  1. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorate.js +8 -0
  2. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorateMetadata.js +5 -0
  3. package/dist/app/Application.d.ts +33 -0
  4. package/dist/app/Application.js +133 -0
  5. package/dist/app/abort.d.ts +8 -0
  6. package/dist/app/abort.js +16 -0
  7. package/dist/app/compression.d.ts +2 -0
  8. package/dist/app/compression.js +35 -0
  9. package/dist/app/config.d.ts +44 -0
  10. package/dist/app/config.js +55 -0
  11. package/dist/app/discovery.d.ts +23 -0
  12. package/dist/app/discovery.js +74 -0
  13. package/dist/app/errors.d.ts +22 -0
  14. package/dist/app/errors.js +57 -0
  15. package/dist/app/logger.d.ts +20 -0
  16. package/dist/app/logger.js +40 -0
  17. package/dist/app/metadata.d.ts +5 -0
  18. package/dist/app/metadata.js +16 -0
  19. package/dist/app/redis.d.ts +4 -0
  20. package/dist/app/redis.js +24 -0
  21. package/dist/auth/credentials.d.ts +6 -0
  22. package/dist/auth/credentials.js +24 -0
  23. package/dist/auth/guards.d.ts +11 -0
  24. package/dist/auth/guards.js +44 -0
  25. package/dist/auth/params.d.ts +8 -0
  26. package/dist/auth/params.js +19 -0
  27. package/dist/auth/secrets.d.ts +6 -0
  28. package/dist/auth/secrets.js +38 -0
  29. package/dist/auth/sessions.d.ts +32 -0
  30. package/dist/auth/sessions.js +49 -0
  31. package/dist/database/data-source.d.ts +7 -0
  32. package/dist/database/data-source.js +15 -0
  33. package/dist/database/models.d.ts +16 -0
  34. package/dist/database/models.js +72 -0
  35. package/dist/database/queries.d.ts +26 -0
  36. package/dist/database/queries.js +56 -0
  37. package/dist/events/Broadcast.d.ts +8 -0
  38. package/dist/events/Broadcast.js +42 -0
  39. package/dist/events/EventBus.d.ts +23 -0
  40. package/dist/events/EventBus.js +115 -0
  41. package/dist/gateway/ConnectionRegistry.d.ts +25 -0
  42. package/dist/gateway/ConnectionRegistry.js +68 -0
  43. package/dist/gateway/Gateway.d.ts +15 -0
  44. package/dist/gateway/Gateway.js +135 -0
  45. package/dist/http/Controller.d.ts +24 -0
  46. package/dist/http/Controller.js +94 -0
  47. package/dist/http/auto-validate-body.d.ts +8 -0
  48. package/dist/http/auto-validate-body.js +16 -0
  49. package/dist/http/call.d.ts +24 -0
  50. package/dist/http/call.js +66 -0
  51. package/dist/http/middleware.d.ts +21 -0
  52. package/dist/http/middleware.js +39 -0
  53. package/dist/http/org-context.d.ts +6 -0
  54. package/dist/http/org-context.js +23 -0
  55. package/dist/http/params.d.ts +38 -0
  56. package/dist/http/params.js +93 -0
  57. package/dist/http/responses.d.ts +20 -0
  58. package/dist/http/responses.js +29 -0
  59. package/dist/queues/BaseQueue.d.ts +15 -0
  60. package/dist/queues/BaseQueue.js +69 -0
  61. package/dist/storage/ObjectStorage.d.ts +37 -0
  62. package/dist/storage/ObjectStorage.js +170 -0
  63. package/dist/testing/harness.d.ts +25 -0
  64. package/dist/testing/harness.js +46 -0
  65. package/dist/testing/rate-limit.d.ts +1 -0
  66. package/dist/testing/rate-limit.js +4 -0
  67. package/dist/testing/request.d.ts +21 -0
  68. package/dist/testing/request.js +41 -0
  69. package/dist/tools/ToolGroup.d.ts +33 -0
  70. package/dist/tools/ToolGroup.js +30 -0
  71. package/package.json +59 -3
  72. 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,5 @@
1
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorateMetadata.js
2
+ function __decorateMetadata(k, v) {
3
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
4
+ }
5
+ export { __decorateMetadata as default };
@@ -0,0 +1,33 @@
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
+ log: ApplicationLog;
15
+ discover: () => Promise<Discovered>;
16
+ createDataSource?: (entities: Function[]) => DataSource;
17
+ plugins?: (app: FastifyInstance) => Promise<void>;
18
+ afterDatabase?: (dataSource: DataSource) => Promise<void>;
19
+ afterMount?: (discovered: Discovered) => void;
20
+ }
21
+ export interface ListenTarget {
22
+ start(): Promise<void>;
23
+ stop(): Promise<void>;
24
+ }
25
+ export default class Application {
26
+ #private;
27
+ constructor(options: ApplicationOptions);
28
+ get dataSource(): DataSource | undefined;
29
+ build({ queues: startQueues }?: BuildOptions): Promise<FastifyInstance>;
30
+ start(): Promise<void>;
31
+ stop(): Promise<void>;
32
+ }
33
+ export declare const listen: (app: ListenTarget, failed?: string) => void;
@@ -0,0 +1,133 @@
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, {
37
+ origin: this.#options.corsOrigins,
38
+ credentials: true,
39
+ methods: [
40
+ "GET",
41
+ "HEAD",
42
+ "POST",
43
+ "PUT",
44
+ "PATCH",
45
+ "DELETE"
46
+ ]
47
+ });
48
+ await this.#app.register(rateLimit, {
49
+ global: false,
50
+ redis,
51
+ nameSpace: "rl:",
52
+ errorResponseBuilder: () => RateLimitError.TooManyRequests()
53
+ });
54
+ registerCompression(this.#app);
55
+ if (this.#options.plugins) await this.#options.plugins(this.#app);
56
+ const discovered = await this.#options.discover();
57
+ await this.#openDatabase(discovered.entities);
58
+ this.#registerErrorHandler();
59
+ this.#registerRequestLogging();
60
+ await this.#mountControllers(discovered.controllers);
61
+ this.#app.get("/health", async () => ({ status: "ok" }));
62
+ this.#mountGateways(discovered.gateways);
63
+ discovered.events.forEach(registerEventGroup);
64
+ this.#options.afterMount?.(discovered);
65
+ if (startQueues) this.#startQueues(discovered.queues);
66
+ return this.#app;
67
+ }
68
+ async start() {
69
+ await this.build();
70
+ await this.#app.listen({
71
+ port: this.#options.port,
72
+ host: "0.0.0.0"
73
+ });
74
+ }
75
+ async stop() {
76
+ await this.#app.close();
77
+ await Promise.all(this.#queues.map((queue) => queue.close()));
78
+ await eventBus.close();
79
+ await broadcast.close();
80
+ await this.#dataSource?.destroy();
81
+ }
82
+ async #openDatabase(entities) {
83
+ if (!this.#options.createDataSource) return;
84
+ this.#dataSource = this.#options.createDataSource(entities);
85
+ await this.#dataSource.initialize();
86
+ if (this.#options.afterDatabase) await this.#options.afterDatabase(this.#dataSource);
87
+ }
88
+ #registerErrorHandler() {
89
+ this.#app.setErrorHandler((err, req, reply) => {
90
+ const answer = err instanceof RuntimeError ? err : ServerError.Internal();
91
+ if (answer.statusCode >= 500) logger.error(`${req.method} ${req.url}`, err, {
92
+ scope: "http",
93
+ statusCode: answer.statusCode
94
+ });
95
+ const payload = { error: answer.message };
96
+ if (err instanceof ValidationError) payload.errors = err.errors;
97
+ reply.status(answer.statusCode).send(payload);
98
+ });
99
+ }
100
+ #registerRequestLogging() {
101
+ this.#app.addHook("onResponse", (req, reply, done) => {
102
+ logger.debug(`${req.method} ${req.url}`, {
103
+ scope: "http",
104
+ statusCode: reply.statusCode,
105
+ ms: Math.round(reply.elapsedTime)
106
+ });
107
+ done();
108
+ });
109
+ }
110
+ async #mountControllers(controllers) {
111
+ for (const { prefix, Controller } of controllers) await new Controller().register(this.#app, prefix);
112
+ }
113
+ #mountGateways(gateways) {
114
+ for (const Gateway of gateways) new Gateway().register(this.#app);
115
+ }
116
+ #startQueues(queues) {
117
+ for (const Queue of queues) {
118
+ const queue = new Queue();
119
+ queue.startWorker();
120
+ this.#queues.push(queue);
121
+ }
122
+ }
123
+ };
124
+ const listen = (app, failed = "Failed to start server") => {
125
+ app.start().catch((err) => {
126
+ logger.error(failed, err);
127
+ process.exit(1);
128
+ });
129
+ for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => {
130
+ app.stop().finally(() => process.exit(0));
131
+ });
132
+ };
133
+ export { Application as default, listen };
@@ -0,0 +1,8 @@
1
+ declare class AbortScope {
2
+ #private;
3
+ run<T>(signal: AbortSignal, work: () => Promise<T>): Promise<T>;
4
+ detached<T>(work: () => Promise<T>): Promise<T>;
5
+ signal(): AbortSignal | undefined;
6
+ }
7
+ export declare const abortScope: AbortScope;
8
+ export {};
@@ -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,2 @@
1
+ import { FastifyInstance } from "fastify";
2
+ export declare const registerCompression: (app: FastifyInstance) => void;
@@ -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,44 @@
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
+ }
18
+ export interface ReadableConfig {
19
+ name: string;
20
+ jwtSecret: string | null;
21
+ redis: ReadableRedisConfig;
22
+ storage: ReadableStorageConfig | null;
23
+ }
24
+ export declare const requiredEnv: (key: string) => string;
25
+ export declare const optionalEnv: (key: string) => string | undefined;
26
+ export declare const configure: (next: ReadableConfig) => void;
27
+ export declare const readableConfig: () => ReadableConfig;
28
+ export declare const jwtSecret: () => string;
29
+ export declare const storageConfig: () => ReadableStorageConfig;
30
+ export declare const serviceConfig: (corsFallback: string) => {
31
+ port: number;
32
+ corsOrigins: string[];
33
+ database: {
34
+ url: string;
35
+ schema: string | undefined;
36
+ synchronize: boolean;
37
+ };
38
+ log: {
39
+ level: string;
40
+ pretty: boolean;
41
+ };
42
+ };
43
+ export declare const redisFromEnv: () => ReadableRedisConfig;
44
+ 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,23 @@
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 declare class ModuleDiscovery {
17
+ #private;
18
+ private readonly modulesDir;
19
+ constructor(modulesDir: string);
20
+ discover(): Promise<Discovered>;
21
+ static merge(parts: Discovered[]): Discovered;
22
+ }
23
+ export declare const discoverFrom: (metaUrl: string, folders?: string[]) => Promise<Discovered>;
@@ -0,0 +1,74 @@
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) {
8
+ this.modulesDir = modulesDir;
9
+ }
10
+ async discover() {
11
+ const names = (await readdir(this.modulesDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
12
+ const discovered = {
13
+ controllers: [],
14
+ entities: [],
15
+ events: [],
16
+ queues: [],
17
+ gateways: [],
18
+ tools: []
19
+ };
20
+ for (const name of names) {
21
+ const controllers = await this.#loadDefaults(name, "controllers");
22
+ discovered.controllers.push(...controllers.map((Controller) => ({
23
+ prefix: getControllerPrefix(Controller) ?? `/${name}`,
24
+ Controller
25
+ })));
26
+ discovered.entities.push(...await this.#loadDefaults(name, "models"));
27
+ discovered.events.push(...await this.#loadDefaults(name, "events"));
28
+ discovered.queues.push(...await this.#loadDefaults(name, "queues"));
29
+ discovered.gateways.push(...await this.#loadDefaults(name, "gateways"));
30
+ discovered.tools.push(...await this.#loadDefaults(name, "tools"));
31
+ }
32
+ return discovered;
33
+ }
34
+ static merge(parts) {
35
+ const discovered = {
36
+ controllers: [],
37
+ entities: [],
38
+ events: [],
39
+ queues: [],
40
+ gateways: [],
41
+ tools: []
42
+ };
43
+ for (const part of parts) {
44
+ discovered.controllers.push(...part.controllers);
45
+ discovered.entities.push(...part.entities);
46
+ discovered.events.push(...part.events);
47
+ discovered.queues.push(...part.queues);
48
+ discovered.gateways.push(...part.gateways);
49
+ discovered.tools.push(...part.tools);
50
+ }
51
+ return discovered;
52
+ }
53
+ async #loadDefaults(moduleName, category) {
54
+ const dir = join(this.modulesDir, moduleName, category);
55
+ let files;
56
+ try {
57
+ files = await readdir(dir);
58
+ } catch {
59
+ return [];
60
+ }
61
+ const loaded = [];
62
+ for (const file of files.sort()) {
63
+ if (!file.endsWith(".ts") || file.endsWith(".d.ts")) continue;
64
+ const imported = await import(pathToFileURL(join(dir, file)).href);
65
+ if (imported.default) loaded.push(imported.default);
66
+ }
67
+ return loaded;
68
+ }
69
+ };
70
+ const discoverFrom = async (metaUrl, folders = ["modules"]) => {
71
+ const srcDir = join(dirname(fileURLToPath(metaUrl)), "..");
72
+ return ModuleDiscovery.merge(await Promise.all(folders.map((folder) => new ModuleDiscovery(join(srcDir, folder)).discover())));
73
+ };
74
+ 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" | "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,57 @@
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
+ InvalidEncryptionKey: 500
41
+ }
42
+ });
43
+ const CryptoError = defineErrors({
44
+ domain: "Crypto",
45
+ causes: {
46
+ EncryptFailed: 400,
47
+ DecryptFailed: 500
48
+ }
49
+ });
50
+ const SchemaError = defineErrors({
51
+ domain: "Schema",
52
+ causes: {
53
+ PendingMigrations: 500,
54
+ Irreversible: 500
55
+ }
56
+ });
57
+ 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,5 @@
1
+ export declare class ClassMetadata<T> {
2
+ #private;
3
+ append(ctor: object, item: T): void;
4
+ get(ctor: object): T[];
5
+ }
@@ -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,4 @@
1
+ import { Redis, RedisOptions } from "ioredis";
2
+ export declare const redisOptions: () => RedisOptions;
3
+ export declare const createRedis: (options?: RedisOptions) => Redis;
4
+ export declare const redis: Redis;
@@ -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 };
@@ -0,0 +1,6 @@
1
+ export declare class PasswordService {
2
+ #private;
3
+ hash(password: string): Promise<string>;
4
+ verify(password: string, stored: string): Promise<boolean>;
5
+ }
6
+ export declare const answersChallenge: (challenge: string, verifier: string) => boolean;