@podosoft/podokit 1.0.2 → 1.1.4

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 (119) hide show
  1. package/README.md +74 -6
  2. package/dist/add.d.ts +14 -1
  3. package/dist/add.js +42 -5
  4. package/dist/create.d.ts +4 -0
  5. package/dist/create.js +9 -0
  6. package/dist/deploy-compose-profile.d.ts +3 -0
  7. package/dist/deploy-compose-profile.js +74 -8
  8. package/dist/deploy-compose-render.d.ts +1 -0
  9. package/dist/deploy-compose-render.js +46 -1
  10. package/dist/deploy-compose.js +2 -1
  11. package/dist/deploy-profile.js +18 -8
  12. package/dist/deploy.js +157 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.js +41 -0
  15. package/dist/lib.d.ts +2 -0
  16. package/dist/lib.js +8 -2
  17. package/dist/lockfile.d.ts +6 -1
  18. package/dist/lockfile.js +22 -4
  19. package/dist/provider.d.ts +24 -0
  20. package/dist/provider.js +142 -0
  21. package/dist/remove.js +6 -3
  22. package/dist/templates/base/AGENTS.md +9 -3
  23. package/dist/templates/base/README.md +12 -8
  24. package/dist/templates/fullstack/AGENTS.md +24 -5
  25. package/dist/templates/fullstack/README.md +75 -11
  26. package/dist/templates/fullstack/apps/api/package.json +4 -3
  27. package/dist/templates/fullstack/apps/api/src/config/env.validation.ts +1 -0
  28. package/dist/templates/fullstack/apps/api/src/config/providers.ts +9 -0
  29. package/dist/templates/fullstack/apps/api/src/core/services.ts +7 -2
  30. package/dist/templates/fullstack/apps/api/src/database/data-source.ts +30 -8
  31. package/dist/templates/fullstack/apps/api/src/database/database.spec.ts +58 -0
  32. package/dist/templates/fullstack/apps/api/src/database/database.ts +58 -2
  33. package/dist/templates/fullstack/apps/api/src/database/migrate.ts +24 -2
  34. package/dist/templates/fullstack/apps/api/src/database/sqlite-migrator.spec.ts +50 -0
  35. package/dist/templates/fullstack/apps/api/src/database/sqlite-migrator.ts +134 -0
  36. package/dist/templates/fullstack/compose.dev.yaml +2 -2
  37. package/dist/templates/fullstack/dot-agents/skills/podokit-deploy/references/profile.md +10 -3
  38. package/dist/templates/fullstack/dot-env.example +2 -0
  39. package/dist/templates/modules/admin-dashboard/files/apps/api/src/admin.module.ts +2 -2
  40. package/dist/templates/modules/admin-dashboard/files/apps/api/src/profile-image/profile-image.service.spec.ts +10 -4
  41. package/dist/templates/modules/admin-dashboard/files/apps/api/src/profile-image/profile-image.service.ts +10 -4
  42. package/dist/templates/modules/admin-dashboard/files/apps/api/src/site-settings/site-settings.service.ts +10 -4
  43. package/dist/templates/modules/admin-dashboard/module.manifest.json +3 -5
  44. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit-enabled.ts +2 -5
  45. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit.migration.spec.ts +33 -0
  46. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit.service.spec.ts +13 -0
  47. package/dist/templates/modules/audit-log/files/apps/api/src/audit/audit.service.ts +17 -8
  48. package/dist/templates/modules/audit-log/files/apps/api/src/migrations/1720300000000-InitAuditLogs.ts +5 -4
  49. package/dist/templates/modules/audit-log/module.manifest.json +1 -1
  50. package/dist/templates/modules/auth/files/apps/api/src/auth/account-issuer-migration.spec.ts +88 -0
  51. package/dist/templates/modules/auth/files/apps/api/src/auth/account-issuer-migration.ts +123 -0
  52. package/dist/templates/modules/auth/files/apps/api/src/auth/auth-config-store.ts +2 -2
  53. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.module.ts +4 -0
  54. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.service.ts +2 -2
  55. package/dist/templates/modules/auth/files/apps/api/src/auth/auth.ts +4 -4
  56. package/dist/templates/modules/auth/files/apps/api/src/auth/db.ts +55 -10
  57. package/dist/templates/modules/auth/files/apps/api/src/auth/feature-gate.ts +10 -14
  58. package/dist/templates/modules/auth/files/apps/api/src/migrate.ts +24 -6
  59. package/dist/templates/modules/auth/files/apps/api/src/migrations/1720400000000-InitAppSettings.ts +2 -1
  60. package/dist/templates/modules/auth/files/apps/api/src/migrations/1720500000000-InitAuthConfig.ts +4 -3
  61. package/dist/templates/modules/auth/files/apps/api/src/settings/app-settings.migration.spec.ts +15 -4
  62. package/dist/templates/modules/auth/files/apps/api/src/settings/auth-config.migration.spec.ts +30 -0
  63. package/dist/templates/modules/auth/module.manifest.json +6 -6
  64. package/dist/templates/modules/bullmq/files/apps/api/src/jobs/bullmq-job.queue.spec.ts +10 -0
  65. package/dist/templates/modules/bullmq/files/apps/api/src/jobs/bullmq-job.queue.ts +107 -0
  66. package/dist/templates/modules/bullmq/files/apps/api/src/jobs/jobs.module.ts +12 -11
  67. package/dist/templates/modules/bullmq/files/apps/api/src/main-worker.ts +5 -0
  68. package/dist/templates/modules/bullmq/module.manifest.json +7 -0
  69. package/dist/templates/modules/cache-memory/files/apps/api/src/cache-memory/cache-memory.module.spec.ts +16 -0
  70. package/dist/templates/modules/cache-memory/files/apps/api/src/cache-memory/cache-memory.module.ts +12 -0
  71. package/dist/templates/modules/cache-memory/module.manifest.json +30 -0
  72. package/dist/templates/modules/events-memory/files/apps/api/src/events-provider-memory/events-memory.module.ts +14 -0
  73. package/dist/templates/modules/events-memory/module.manifest.json +30 -0
  74. package/dist/templates/modules/events-redis/files/apps/api/src/events-provider-redis/events-redis.module.ts +16 -0
  75. package/dist/templates/modules/events-redis/files/apps/api/src/events-provider-redis/redis-event.bus.ts +75 -0
  76. package/dist/templates/modules/events-redis/module.manifest.json +32 -0
  77. package/dist/templates/modules/file-upload/files/apps/api/src/files/files.module.ts +9 -5
  78. package/dist/templates/modules/file-upload/files/tests/api/files.api.spec.ts +1 -1
  79. package/dist/templates/modules/file-upload/module.manifest.json +4 -3
  80. package/dist/templates/modules/job-progress/files/apps/api/src/progress/job-progress.module.ts +36 -14
  81. package/dist/templates/modules/job-progress/files/apps/api/src/progress/progress.bridge.spec.ts +9 -32
  82. package/dist/templates/modules/job-progress/files/apps/api/src/progress/progress.processor.ts +16 -11
  83. package/dist/templates/modules/job-progress/module.manifest.json +7 -8
  84. package/dist/templates/modules/jobs-local/files/apps/api/src/jobs-local/jobs-local.module.ts +42 -0
  85. package/dist/templates/modules/jobs-local/files/apps/api/src/jobs-local/local-job.queue.spec.ts +45 -0
  86. package/dist/templates/modules/jobs-local/files/apps/api/src/jobs-local/local-job.queue.ts +212 -0
  87. package/dist/templates/modules/jobs-local/module.manifest.json +34 -0
  88. package/dist/templates/modules/mailer/files/apps/api/src/mail/mailer.ts +7 -3
  89. package/dist/templates/modules/mailer/module.manifest.json +2 -4
  90. package/dist/templates/modules/object-storage-local/files/apps/api/src/storage-local/storage-local.module.spec.ts +25 -0
  91. package/dist/templates/modules/object-storage-local/files/apps/api/src/storage-local/storage-local.module.ts +60 -0
  92. package/dist/templates/modules/object-storage-local/module.manifest.json +34 -0
  93. package/dist/templates/modules/object-storage-s3/files/apps/api/src/storage/s3-object.store.ts +50 -0
  94. package/dist/templates/modules/object-storage-s3/files/apps/api/src/storage/storage.module.ts +8 -0
  95. package/dist/templates/modules/object-storage-s3/files/infra/docker/minio.compose.yml +4 -4
  96. package/dist/templates/modules/object-storage-s3/files/tests/api/storage.api.spec.ts +20 -12
  97. package/dist/templates/modules/object-storage-s3/module.manifest.json +4 -2
  98. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.module.spec.ts +14 -1
  99. package/dist/templates/modules/rate-limit/files/apps/api/src/rate-limit/rate-limit.module.ts +18 -37
  100. package/dist/templates/modules/rate-limit/files/tests/api/rate-limit.api.spec.ts +12 -0
  101. package/dist/templates/modules/rate-limit/module.manifest.json +8 -6
  102. package/dist/templates/modules/redis/files/apps/api/src/redis/redis-cache.store.ts +82 -0
  103. package/dist/templates/modules/redis/files/apps/api/src/redis/redis.module.ts +6 -0
  104. package/dist/templates/modules/redis/module.manifest.json +2 -0
  105. package/dist/templates/modules/sse/files/apps/api/src/events/events.module.ts +5 -6
  106. package/dist/templates/modules/sse/files/apps/api/src/events/events.service.spec.ts +4 -4
  107. package/dist/templates/modules/sse/files/apps/api/src/events/events.service.ts +6 -5
  108. package/dist/templates/modules/sse/module.manifest.json +4 -6
  109. package/dist/templates/todo/AGENTS.md +25 -6
  110. package/dist/templates/todo/README.md +72 -14
  111. package/dist/templates/todo/apps/api/src/migrations/1720100000000-InitTodos.ts +11 -0
  112. package/dist/templates/todo/apps/api/src/todos/todo.repository.spec.ts +76 -0
  113. package/dist/templates/todo/apps/api/src/todos/todo.repository.ts +9 -4
  114. package/dist/templates/todo/tests/api/todo.api.spec.ts +32 -0
  115. package/dist/templates/todo/tests/ui/todo.ui.spec.ts +31 -0
  116. package/package.json +2 -1
  117. package/dist/templates/modules/job-progress/files/apps/api/src/progress/progress.bridge.ts +0 -32
  118. package/dist/templates/modules/mailer/files/apps/api/src/mail/db.ts +0 -13
  119. package/dist/templates/modules/sse/files/apps/api/src/events/events.transport.ts +0 -111
@@ -0,0 +1,76 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { SQL } from "bun";
3
+ import { Database as SqliteDatabase } from "bun:sqlite";
4
+ import { mkdtempSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import {
8
+ revertLatestSqliteMigration,
9
+ runSqliteMigrations,
10
+ type SqliteMigrationDefinition,
11
+ } from "../database/sqlite-migrator";
12
+ import { InitTodos1720100000000 } from "../migrations/1720100000000-InitTodos";
13
+ import { TodoRepository } from "./todo.repository";
14
+
15
+ const migrations: readonly SqliteMigrationDefinition[] = [
16
+ { timestamp: 1720100000000, migration: new InitTodos1720100000000() },
17
+ ];
18
+
19
+ describe("Todo SQLite persistence", () => {
20
+ it("preserves boolean and Date rows returned by PostgreSQL", async (): Promise<void> => {
21
+ const row = {
22
+ id: crypto.randomUUID(),
23
+ title: "Existing task",
24
+ completed: true,
25
+ createdAt: new Date("2026-10-07T00:00:00.000Z"),
26
+ };
27
+ const sql = ((): Promise<typeof row[]> => Promise.resolve([row])) as unknown as SQL;
28
+ expect(await new TodoRepository(sql).find(row.id)).toEqual({
29
+ ...row,
30
+ createdAt: "2026-10-07T00:00:00.000Z",
31
+ });
32
+ });
33
+
34
+ it("applies the initial migration once and reverts it", async (): Promise<void> => {
35
+ const database = new SqliteDatabase(":memory:");
36
+ try {
37
+ await runSqliteMigrations(database, migrations);
38
+ await runSqliteMigrations(database, migrations);
39
+ expect(database.query<{ count: number }, []>("SELECT count(*) AS count FROM migrations").get()?.count).toBe(1);
40
+ expect(database.query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE name = 'todos'").get()?.name).toBe("todos");
41
+ expect(await revertLatestSqliteMigration(database, migrations)).toBe(true);
42
+ expect(database.query("SELECT name FROM sqlite_master WHERE name = 'todos'").get()).toBeNull();
43
+ } finally {
44
+ database.close();
45
+ }
46
+ });
47
+
48
+ it("creates, reads, updates, and removes records with stable API types", async (): Promise<void> => {
49
+ const directory = mkdtempSync(join(tmpdir(), "podokit-todo-"));
50
+ const path = join(directory, "podokit.sqlite");
51
+ const database = new SqliteDatabase(path);
52
+ let sql: SQL | undefined;
53
+ try {
54
+ await runSqliteMigrations(database, migrations);
55
+ sql = new SQL(`sqlite://${path}`, { adapter: "sqlite" });
56
+ const repository = new TodoRepository(sql);
57
+ const todo = await repository.create("First task");
58
+ expect(todo.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
59
+ expect(todo.completed).toBe(false);
60
+ expect(new Date(todo.createdAt).toISOString()).toBe(todo.createdAt);
61
+ expect(await repository.find(todo.id)).toEqual(todo);
62
+ expect(await repository.all()).toEqual([todo]);
63
+
64
+ const updated = await repository.update(todo.id, { title: "Completed task", completed: true });
65
+ expect(updated).toEqual({ ...todo, title: "Completed task", completed: true });
66
+ expect(await repository.remove(todo.id)).toBe(true);
67
+ expect(await repository.find(todo.id)).toBeNull();
68
+ expect(await repository.update(todo.id, { completed: false })).toBeNull();
69
+ expect(await repository.remove(todo.id)).toBe(false);
70
+ } finally {
71
+ await sql?.close();
72
+ database.close();
73
+ rmSync(directory, { recursive: true, force: true });
74
+ }
75
+ });
76
+ });
@@ -10,12 +10,16 @@ export interface TodoRecord {
10
10
  interface TodoRow {
11
11
  id: string;
12
12
  title: string;
13
- completed: boolean;
14
- createdAt: Date;
13
+ completed: boolean | number;
14
+ createdAt: Date | string;
15
15
  }
16
16
 
17
17
  function record(row: TodoRow): TodoRecord {
18
- return { ...row, createdAt: row.createdAt.toISOString() };
18
+ return {
19
+ ...row,
20
+ completed: Boolean(row.completed),
21
+ createdAt: (row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt)).toISOString(),
22
+ };
19
23
  }
20
24
 
21
25
  export class TodoRepository {
@@ -39,8 +43,9 @@ export class TodoRepository {
39
43
  }
40
44
 
41
45
  async create(title: string): Promise<TodoRecord> {
46
+ const id = crypto.randomUUID();
42
47
  const rows = await this.sql<TodoRow[]>`
43
- INSERT INTO todos (title) VALUES (${title})
48
+ INSERT INTO todos (id, title) VALUES (${id}, ${title})
44
49
  RETURNING id, title, completed, "createdAt"
45
50
  `;
46
51
  const row = rows[0];
@@ -0,0 +1,32 @@
1
+ import { expect, test } from "@playwright/test";
2
+
3
+ test("Todo CRUD preserves UUIDs, booleans, and timestamps @smoke", async ({ request, baseURL }): Promise<void> => {
4
+ const title = `Todo API ${crypto.randomUUID()}`;
5
+ const headers = { Origin: baseURL ?? "http://localhost:5001" };
6
+ const response = await request.post("/api/todos", { data: { title }, headers });
7
+ expect(response.status()).toBe(201);
8
+ const created: unknown = await response.json();
9
+ expect(created).toMatchObject({ title, completed: false, id: expect.any(String), createdAt: expect.any(String) });
10
+ if (typeof created !== "object" || created === null || !("id" in created) || typeof created.id !== "string"
11
+ || !("createdAt" in created) || typeof created.createdAt !== "string") {
12
+ throw new Error("Todo response must include an ID and timestamp");
13
+ }
14
+ const id = created.id;
15
+ try {
16
+ expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
17
+ expect(new Date(created.createdAt).toISOString()).toBe(created.createdAt);
18
+ const list = await request.get("/api/todos");
19
+ expect(list.status()).toBe(200);
20
+ expect(await list.json()).toEqual(expect.arrayContaining([created]));
21
+
22
+ const update = await request.patch(`/api/todos/${id}`, { data: { title: `${title} updated`, completed: true }, headers });
23
+ expect(update.status()).toBe(200);
24
+ expect(await update.json()).toEqual({ ...created, title: `${title} updated`, completed: true });
25
+ expect((await request.delete(`/api/todos/${id}`, { headers })).status()).toBe(204);
26
+ expect((await request.get(`/api/todos/${id}`)).status()).toBe(404);
27
+ expect((await request.patch(`/api/todos/${id}`, { data: { completed: false }, headers })).status()).toBe(404);
28
+ expect((await request.delete(`/api/todos/${id}`, { headers })).status()).toBe(404);
29
+ } finally {
30
+ await request.delete(`/api/todos/${id}`, { headers });
31
+ }
32
+ });
@@ -0,0 +1,31 @@
1
+ import { expect, test } from "@playwright/test";
2
+
3
+ test("Todo items persist through create, complete, reload, and delete @smoke", async ({ page, request, baseURL }): Promise<void> => {
4
+ const title = `Todo UI ${crypto.randomUUID()}`;
5
+ try {
6
+ await page.goto("/");
7
+ await page.getByPlaceholder("Add a todo…").fill(title);
8
+ await page.getByRole("button", { name: "Add", exact: true }).click();
9
+ const row = page.getByRole("listitem").filter({ hasText: title });
10
+ await expect(row).toBeVisible();
11
+ await expect(row.getByRole("checkbox")).not.toBeChecked();
12
+ await row.getByRole("checkbox").check();
13
+ await expect(row.getByRole("checkbox")).toBeChecked();
14
+ await page.reload();
15
+ await expect(row.getByRole("checkbox")).toBeChecked();
16
+ await row.getByRole("button", { name: "Delete", exact: true }).click();
17
+ await expect(row).toHaveCount(0);
18
+ await page.reload();
19
+ await expect(row).toHaveCount(0);
20
+ } finally {
21
+ const items: unknown = await (await request.get("/api/todos")).json();
22
+ if (Array.isArray(items)) {
23
+ for (const item of items as unknown[]) {
24
+ if (typeof item === "object" && item !== null && "title" in item && item.title === title
25
+ && "id" in item && typeof item.id === "string") {
26
+ await request.delete(`/api/todos/${item.id}`, { headers: { Origin: baseURL ?? "http://localhost:5001" } });
27
+ }
28
+ }
29
+ }
30
+ }
31
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@podosoft/podokit",
3
- "version": "1.0.2",
3
+ "version": "1.1.4",
4
4
  "description": "An opinionated Bun and Elysia full-stack TypeScript starter toolkit and CLI with SvelteKit, TailwindCSS, shadcn-svelte, Docker, and k3s.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -45,6 +45,7 @@
45
45
  "test": "vitest run"
46
46
  },
47
47
  "dependencies": {
48
+ "@podosoft/podokit-runtime": "^0.2.0",
48
49
  "@podosoft/podokit-template-engine": "^0.4.2"
49
50
  }
50
51
  }
@@ -1,32 +0,0 @@
1
- import { RedisService } from "../redis/redis.service";
2
- import { EventsService } from "../events/events.service";
3
- import { PROGRESS_CHANNEL } from "./progress.processor";
4
-
5
- // Runs in the API process: relays worker progress (Redis pub/sub) to SSE.
6
- export class ProgressBridge {
7
- private unsubscribe?: () => Promise<void>;
8
-
9
- constructor(
10
- private readonly redis: RedisService,
11
- private readonly events: EventsService,
12
- ) {}
13
-
14
- async connect(): Promise<void> {
15
- this.unsubscribe = await this.redis.subscribe(PROGRESS_CHANNEL, (message) => {
16
- try {
17
- const parsed: unknown = JSON.parse(message);
18
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
19
- process.stderr.write("Discard invalid job progress event\n");
20
- return;
21
- }
22
- this.events.publishLocal({ type: "job-progress", ...parsed });
23
- } catch {
24
- process.stderr.write("Discard malformed job progress event\n");
25
- }
26
- });
27
- }
28
-
29
- async close(): Promise<void> {
30
- await this.unsubscribe?.();
31
- }
32
- }
@@ -1,13 +0,0 @@
1
- import { Pool } from "pg";
2
-
3
- // The mailer's own pg pool, in its own module so the mailer stays independent of
4
- // any other module. Used only to read the optional admin-configured SMTP settings
5
- // from `auth_config` when the auth module is present; with no such table the read
6
- // fails softly and the mailer falls back to SMTP_* env (see mailer.ts).
7
- export const pool = new Pool({
8
- host: process.env.POSTGRES_HOST ?? "localhost",
9
- port: Number(process.env.POSTGRES_PORT ?? 5432),
10
- user: process.env.POSTGRES_USER ?? "podokit",
11
- password: process.env.POSTGRES_PASSWORD ?? "podokit",
12
- database: process.env.POSTGRES_DB ?? "podokit",
13
- });
@@ -1,111 +0,0 @@
1
- import { RedisClient } from "bun";
2
- import { redisConnectionUrl } from "../config/redis.connection";
3
-
4
- export type EventHandler = (data: unknown) => void;
5
-
6
- export interface EventsTransport {
7
- connect(handler: EventHandler): Promise<void>;
8
- publish(data: unknown): Promise<void>;
9
- ready(): Promise<void>;
10
- close(): Promise<void>;
11
- }
12
-
13
- function maxEventBytes(env: NodeJS.ProcessEnv): number {
14
- const value = Number(env.SSE_MAX_EVENT_BYTES ?? 65_536);
15
- if (!Number.isInteger(value) || value < 1) {
16
- throw new Error("SSE_MAX_EVENT_BYTES must be a positive integer");
17
- }
18
- return value;
19
- }
20
-
21
- function encodedEvent(data: unknown, maximumBytes: number): string {
22
- const message = JSON.stringify(data);
23
- if (message === undefined) throw new Error("Event data must be JSON serializable");
24
- if (Buffer.byteLength(message, "utf8") > maximumBytes) {
25
- throw new Error("Event data exceeds SSE_MAX_EVENT_BYTES");
26
- }
27
- return message;
28
- }
29
-
30
- export class MemoryEventsTransport implements EventsTransport {
31
- private handler?: EventHandler;
32
- private readonly maximumBytes: number;
33
-
34
- constructor(env: NodeJS.ProcessEnv = process.env) {
35
- this.maximumBytes = maxEventBytes(env);
36
- }
37
-
38
- connect(handler: EventHandler): Promise<void> {
39
- this.handler = handler;
40
- return Promise.resolve();
41
- }
42
-
43
- async publish(data: unknown): Promise<void> {
44
- this.handler?.(JSON.parse(encodedEvent(data, this.maximumBytes)) as unknown);
45
- }
46
-
47
- ready(): Promise<void> {
48
- return Promise.resolve();
49
- }
50
-
51
- close(): Promise<void> {
52
- this.handler = undefined;
53
- return Promise.resolve();
54
- }
55
- }
56
-
57
- export class RedisEventsTransport implements EventsTransport {
58
- private readonly publisher: RedisClient;
59
- private readonly subscriber: RedisClient;
60
- private readonly channel: string;
61
- private readonly maximumBytes: number;
62
- private handler?: EventHandler;
63
- private listener?: (message: string) => void;
64
-
65
- constructor(env: NodeJS.ProcessEnv = process.env) {
66
- const url = redisConnectionUrl(env);
67
- this.publisher = new RedisClient(url, { connectionTimeout: 5_000 });
68
- this.subscriber = new RedisClient(url, { connectionTimeout: 5_000 });
69
- this.channel = env.SSE_REDIS_CHANNEL?.trim() || "podokit:events";
70
- this.maximumBytes = maxEventBytes(env);
71
- }
72
-
73
- async connect(handler: EventHandler): Promise<void> {
74
- this.handler = handler;
75
- this.listener = (message: string): void => {
76
- if (Buffer.byteLength(message, "utf8") > this.maximumBytes) return;
77
- try {
78
- this.handler?.(JSON.parse(message) as unknown);
79
- } catch {
80
- process.stderr.write("Discard malformed event transport message\n");
81
- }
82
- };
83
- await Promise.all([this.publisher.connect(), this.subscriber.connect()]);
84
- await this.subscriber.subscribe(this.channel, this.listener);
85
- await this.ready();
86
- }
87
-
88
- async publish(data: unknown): Promise<void> {
89
- await this.publisher.publish(this.channel, encodedEvent(data, this.maximumBytes));
90
- }
91
-
92
- async ready(): Promise<void> {
93
- if (!this.subscriber.connected) throw new Error("Redis event subscriber is not ready");
94
- await this.publisher.ping();
95
- }
96
-
97
- async close(): Promise<void> {
98
- if (this.listener) await this.subscriber.unsubscribe(this.channel, this.listener);
99
- this.handler = undefined;
100
- this.listener = undefined;
101
- this.publisher.close();
102
- this.subscriber.close();
103
- }
104
- }
105
-
106
- export function createEventsTransport(env: NodeJS.ProcessEnv = process.env): EventsTransport {
107
- const name = env.SSE_TRANSPORT?.trim().toLowerCase() || "memory";
108
- if (name === "memory") return new MemoryEventsTransport(env);
109
- if (name === "redis") return new RedisEventsTransport(env);
110
- throw new Error('SSE_TRANSPORT must be either "memory" or "redis"');
111
- }