@pollium/readable 0.1.0 → 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.
@@ -11,6 +11,7 @@ export interface ApplicationLog {
11
11
  export interface ApplicationOptions {
12
12
  port: number;
13
13
  corsOrigins: string[];
14
+ publicPaths?: string[];
14
15
  log: ApplicationLog;
15
16
  discover: () => Promise<Discovered>;
16
17
  createDataSource?: (entities: Function[]) => DataSource;
@@ -33,18 +33,21 @@ var Application = class {
33
33
  "uniquelocal"
34
34
  ]
35
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
- });
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
+ } });
48
51
  await this.#app.register(rateLimit, {
49
52
  global: false,
50
53
  redis,
@@ -14,6 +14,7 @@ export interface ReadableDatabaseConfig {
14
14
  url: string;
15
15
  schema: string | undefined;
16
16
  synchronize: boolean;
17
+ timestamptz?: boolean;
17
18
  }
18
19
  export interface ReadableConfig {
19
20
  name: string;
@@ -13,11 +13,15 @@ export interface Discovered {
13
13
  gateways: Array<new () => BaseGateway>;
14
14
  tools: Array<new () => object>;
15
15
  }
16
+ export type ModuleLoader = (url: string) => Promise<{
17
+ default?: unknown;
18
+ }>;
16
19
  export declare class ModuleDiscovery {
17
20
  #private;
18
21
  private readonly modulesDir;
19
- constructor(modulesDir: string);
22
+ private readonly load;
23
+ constructor(modulesDir: string, load: ModuleLoader);
20
24
  discover(): Promise<Discovered>;
21
25
  static merge(parts: Discovered[]): Discovered;
22
26
  }
23
- export declare const discoverFrom: (metaUrl: string, folders?: string[]) => Promise<Discovered>;
27
+ export declare const discoverFrom: (metaUrl: string, load: ModuleLoader, folders?: string[]) => Promise<Discovered>;
@@ -4,8 +4,9 @@ import { dirname, join } from "node:path";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
5
  // lib/app/discovery.ts
6
6
  var ModuleDiscovery = class {
7
- constructor(modulesDir) {
7
+ constructor(modulesDir, load) {
8
8
  this.modulesDir = modulesDir;
9
+ this.load = load;
9
10
  }
10
11
  async discover() {
11
12
  const names = (await readdir(this.modulesDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
@@ -61,14 +62,14 @@ var ModuleDiscovery = class {
61
62
  const loaded = [];
62
63
  for (const file of files.sort()) {
63
64
  if (!file.endsWith(".ts") || file.endsWith(".d.ts")) continue;
64
- const imported = await import(pathToFileURL(join(dir, file)).href);
65
+ const imported = await this.load(pathToFileURL(join(dir, file)).href);
65
66
  if (imported.default) loaded.push(imported.default);
66
67
  }
67
68
  return loaded;
68
69
  }
69
70
  };
70
- const discoverFrom = async (metaUrl, folders = ["modules"]) => {
71
+ const discoverFrom = async (metaUrl, load, folders = ["modules"]) => {
71
72
  const srcDir = join(dirname(fileURLToPath(metaUrl)), "..");
72
- return ModuleDiscovery.merge(await Promise.all(folders.map((folder) => new ModuleDiscovery(join(srcDir, folder)).discover())));
73
+ return ModuleDiscovery.merge(await Promise.all(folders.map((folder) => new ModuleDiscovery(join(srcDir, folder), load).discover())));
73
74
  };
74
75
  export { ModuleDiscovery, discoverFrom };
@@ -16,7 +16,7 @@ export declare const GatewayError: Record<"Internal" | "MissingChannel" | "Malfo
16
16
  export declare const RateLimitError: Record<"TooManyRequests", ErrorFactory>;
17
17
  export declare const RouteError: Record<"PrefixMismatch", ErrorFactory>;
18
18
  export declare const EventError: Record<"UndefinedGroup", ErrorFactory>;
19
- export declare const ConfigError: Record<"MissingEnv" | "InvalidEncryptionKey", ErrorFactory>;
19
+ export declare const ConfigError: Record<"MissingEnv" | "InvalidEnv" | "InvalidEncryptionKey", ErrorFactory>;
20
20
  export declare const CryptoError: Record<"EncryptFailed" | "DecryptFailed", ErrorFactory>;
21
21
  export declare const SchemaError: Record<"PendingMigrations" | "Irreversible", ErrorFactory>;
22
22
  export {};
@@ -37,6 +37,7 @@ const ConfigError = defineErrors({
37
37
  domain: "Config",
38
38
  causes: {
39
39
  MissingEnv: 500,
40
+ InvalidEnv: 500,
40
41
  InvalidEncryptionKey: 500
41
42
  }
42
43
  });
@@ -14,7 +14,7 @@ declare module 'fastify' {
14
14
  }
15
15
  export interface SessionCutoffStore {
16
16
  cutoffOf(userId: string): Promise<number | null>;
17
- cut(userId: string): Promise<void>;
17
+ cut(userId: string, at?: number): Promise<void>;
18
18
  }
19
19
  export declare const SESSION_TTL_SECONDS: number;
20
20
  export declare class JWTService {
@@ -26,7 +26,7 @@ export declare class JWTService {
26
26
  export declare class RedisSessionCutoffStore implements SessionCutoffStore {
27
27
  #private;
28
28
  cutoffOf(userId: string): Promise<number | null>;
29
- cut(userId: string): Promise<void>;
29
+ cut(userId: string, at?: number): Promise<void>;
30
30
  }
31
31
  export declare const sessionCutoffs: SessionCutoffStore;
32
32
  export declare const verifiedSession: (token: string) => Promise<TokenPayload>;
@@ -28,8 +28,8 @@ var RedisSessionCutoffStore = class {
28
28
  const value = await redis.get(`${this.#prefix}${userId}`);
29
29
  return value === null ? null : Number(value);
30
30
  }
31
- async cut(userId) {
32
- await redis.set(`${this.#prefix}${userId}`, String(Math.floor(Date.now() / 1e3)), "EX", SESSION_TTL_SECONDS);
31
+ async cut(userId, at = Math.floor(Date.now() / 1e3)) {
32
+ await redis.set(`${this.#prefix}${userId}`, String(at), "EX", SESSION_TTL_SECONDS);
33
33
  }
34
34
  };
35
35
  const sessionCutoffs = new RedisSessionCutoffStore();
@@ -1,15 +1,22 @@
1
1
  import { DataSource } from "typeorm";
2
2
  // lib/database/data-source.ts
3
- const createDataSource = (database, entities, migrations) => new DataSource({
4
- type: "postgres",
5
- url: database.url,
6
- schema: database.schema,
7
- synchronize: database.synchronize,
8
- entities,
9
- migrations: migrations?.migrations ?? [],
10
- ...migrations === void 0 ? {} : {
11
- migrationsTableName: migrations.tableName,
12
- migrationsTransactionMode: "all"
13
- }
14
- });
3
+ const createDataSource = (database, entities, migrations) => {
4
+ const dataSource = new DataSource({
5
+ type: "postgres",
6
+ url: database.url,
7
+ schema: database.schema,
8
+ synchronize: database.synchronize,
9
+ entities,
10
+ migrations: migrations?.migrations ?? [],
11
+ ...migrations === void 0 ? {} : {
12
+ migrationsTableName: migrations.tableName,
13
+ migrationsTransactionMode: "all"
14
+ }
15
+ });
16
+ if (database.timestamptz) Object.assign(dataSource.driver.mappedDataTypes, {
17
+ createDate: "timestamptz",
18
+ updateDate: "timestamptz"
19
+ });
20
+ return dataSource;
21
+ };
15
22
  export { createDataSource };
@@ -6,6 +6,11 @@ export interface RouteDefinition {
6
6
  method: HttpMethod;
7
7
  handlerName: string | symbol;
8
8
  absolute: boolean;
9
+ bodyLimit?: number;
10
+ }
11
+ export interface RouteOptions {
12
+ method?: HttpMethod;
13
+ bodyLimit?: number;
9
14
  }
10
15
  export interface StatusBinding {
11
16
  handlerName: string | symbol;
@@ -15,7 +20,7 @@ export type Handler = (req: FastifyRequest<RouteGenericInterface>, reply: Fastif
15
20
  export declare const routesByController: ClassMetadata<RouteDefinition>;
16
21
  export declare const Controller: (prefix: string) => ClassDecorator;
17
22
  export declare const getControllerPrefix: (ctor: object) => string | undefined;
18
- export declare const Route: <I, O>(route: string | Endpoint<I, O>, method?: HttpMethod) => MethodDecorator;
23
+ export declare const Route: <I, O>(route: string | Endpoint<I, O>, options?: HttpMethod | RouteOptions) => MethodDecorator;
19
24
  export declare const Status: (code: number) => MethodDecorator;
20
25
  export declare const getStatus: (ctor: object, handlerName: string | symbol) => number | undefined;
21
26
  export default abstract class BaseController {
@@ -15,8 +15,9 @@ const Controller = (prefix) => {
15
15
  const getControllerPrefix = (ctor) => {
16
16
  return prefixByController.get(ctor);
17
17
  };
18
- const Route = (route, method = "GET") => {
18
+ const Route = (route, options = "GET") => {
19
19
  return (target, handlerName) => {
20
+ const { method = "GET", bodyLimit } = typeof options === "string" ? { method: options } : options;
20
21
  const definition = typeof route === "string" ? {
21
22
  path: route,
22
23
  method,
@@ -28,6 +29,7 @@ const Route = (route, method = "GET") => {
28
29
  };
29
30
  routesByController.append(target.constructor, {
30
31
  ...definition,
32
+ bodyLimit,
31
33
  handlerName
32
34
  });
33
35
  };
@@ -53,6 +55,7 @@ var BaseController = class {
53
55
  scope.route({
54
56
  method: route.method,
55
57
  url,
58
+ bodyLimit: route.bodyLimit,
56
59
  config: { rateLimit: getRateLimit(this.constructor, route.handlerName) },
57
60
  preHandler: middlewares.map((mw) => async (req, reply) => await mw(req, reply)),
58
61
  handler
@@ -30,8 +30,10 @@ export declare const parseBody: <T>(validate: BodyValidator<T>, body: unknown) =
30
30
  export declare const Body: <T>(validate?: BodyValidator<T>) => ParameterDecorator;
31
31
  export declare const IdParam: (name: string) => ParameterDecorator;
32
32
  export declare const OrdinalParam: (name: string) => ParameterDecorator;
33
+ export declare const Req: () => ParameterDecorator;
34
+ export declare const Reply: () => ParameterDecorator;
33
35
  export declare const Param: (name: string) => ParameterDecorator;
34
- export declare const Query: (name: string) => ParameterDecorator;
36
+ export declare const Query: (name?: string) => ParameterDecorator;
35
37
  export declare const IdQuery: (name: string) => ParameterDecorator;
36
38
  export declare const OptionalIdQuery: (name: string) => ParameterDecorator;
37
39
  export declare const Pagination: (options?: PaginationOptions) => ParameterDecorator;
@@ -68,8 +68,10 @@ const parseBody = (validate, body) => {
68
68
  const Body = (validate) => createParamDecorator((req) => validate ? parseBody(validate, req.body) : req.body);
69
69
  const IdParam = (name) => createParamDecorator((req) => parseId(req.params[name]));
70
70
  const OrdinalParam = (name) => createParamDecorator((req) => parseOrdinal(req.params[name]));
71
+ const Req = () => createParamDecorator((req) => req);
72
+ const Reply = () => createParamDecorator((_req, reply) => reply);
71
73
  const Param = (name) => createParamDecorator((req) => req.params[name]);
72
- const Query = (name) => createParamDecorator((req) => req.query[name]);
74
+ const Query = (name) => createParamDecorator((req) => name === void 0 ? req.query : req.query[name]);
73
75
  const IdQuery = (name) => createParamDecorator((req) => parseId(req.query[name]));
74
76
  const OptionalIdQuery = (name) => createParamDecorator((req) => {
75
77
  const raw = req.query[name];
@@ -90,4 +92,4 @@ const UploadedFile = () => createParamDecorator(async (req) => {
90
92
  throw error;
91
93
  }
92
94
  });
93
- export { Body, IdParam, IdQuery, OptionalIdQuery, OrdinalParam, Pagination, Param, Query, UploadedFile, bindingsByController, createParamDecorator, getParamResolvers, parseBody, parseId, parseOrdinal, parsePagination };
95
+ export { Body, IdParam, IdQuery, OptionalIdQuery, OrdinalParam, Pagination, Param, Query, Reply, Req, UploadedFile, bindingsByController, createParamDecorator, getParamResolvers, parseBody, parseId, parseOrdinal, parsePagination };
@@ -0,0 +1,9 @@
1
+ import { JobsOptions } from "bullmq";
2
+ export default class QueueProducer<T> {
3
+ #private;
4
+ private readonly name;
5
+ private readonly jobOptions;
6
+ constructor(name: string, jobOptions?: JobsOptions);
7
+ add(data: T, options?: JobsOptions): Promise<void>;
8
+ close(): Promise<void>;
9
+ }
@@ -0,0 +1,21 @@
1
+ import { redisOptions } from "../app/redis.js";
2
+ import { Queue } from "bullmq";
3
+ // lib/queues/QueueProducer.ts
4
+ var QueueProducer = class {
5
+ #queue;
6
+ constructor(name, jobOptions = {}) {
7
+ this.name = name;
8
+ this.jobOptions = jobOptions;
9
+ }
10
+ async add(data, options = {}) {
11
+ this.#queue ??= new Queue(this.name, { connection: redisOptions() });
12
+ await this.#queue.add(this.name, data, {
13
+ ...this.jobOptions,
14
+ ...options
15
+ });
16
+ }
17
+ async close() {
18
+ await this.#queue?.close();
19
+ }
20
+ };
21
+ export { QueueProducer as default };
@@ -1 +1,2 @@
1
- export declare const rateLimitStore: any;
1
+ import { FastifyRateLimitStore } from "@fastify/rate-limit";
2
+ export declare const rateLimitStore: FastifyRateLimitStore;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pollium/readable",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The TypeScript framework for the AI era.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -26,17 +26,17 @@
26
26
  "@fastify/rate-limit": "^11.2.2",
27
27
  "@fastify/websocket": "11.3.0",
28
28
  "bullmq": "^5.80.6",
29
- "fastify": "^5.12.5",
30
29
  "ioredis": "^5.11.1",
31
30
  "jsonwebtoken": "^9.0.3",
32
- "pg": "^8.23.1",
33
31
  "pino": "^10.3.1",
34
- "typeorm": "^1.1.0",
35
32
  "typia": "^12.1.1",
36
33
  "uuid": "^14.0.2",
37
- "@pollium/readable-contracts": "0.1.0"
34
+ "@pollium/readable-contracts": "0.2.0"
38
35
  },
39
36
  "peerDependencies": {
37
+ "fastify": "^5.12.5",
38
+ "pg": "^8.22.0",
39
+ "typeorm": "^1.1.0",
40
40
  "vitest": "^4.1.10"
41
41
  },
42
42
  "peerDependenciesMeta": {
@@ -48,8 +48,11 @@
48
48
  "@types/jsonwebtoken": "^9.0.10",
49
49
  "@types/node": "^26.1.1",
50
50
  "@types/ws": "^8.18.2",
51
+ "fastify": "^5.12.5",
51
52
  "oxlint": "^1.71.0",
53
+ "pg": "^8.23.1",
52
54
  "reflect-metadata": "^0.2.2",
55
+ "typeorm": "^1.1.0",
53
56
  "typescript": "~6.0.2",
54
57
  "vitest": "^4.1.10"
55
58
  },