express-file-cluster 0.3.14 → 0.5.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 (116) hide show
  1. package/README.md +204 -52
  2. package/dist/auth/index.cjs +12 -2
  3. package/dist/auth/index.cjs.map +1 -1
  4. package/dist/auth/index.d.cts +13 -2
  5. package/dist/auth/index.d.ts +13 -2
  6. package/dist/auth/index.js +12 -2
  7. package/dist/chunk-3VWD2ZED.js +60 -0
  8. package/dist/chunk-3VWD2ZED.js.map +1 -0
  9. package/dist/chunk-47K2532L.cjs +196 -0
  10. package/dist/chunk-47K2532L.cjs.map +1 -0
  11. package/dist/chunk-5PDAWMGF.js +438 -0
  12. package/dist/chunk-5PDAWMGF.js.map +1 -0
  13. package/dist/chunk-7YEX4MQV.cjs +38 -0
  14. package/dist/chunk-7YEX4MQV.cjs.map +1 -0
  15. package/dist/chunk-ALBDM5R3.cjs +60 -0
  16. package/dist/chunk-ALBDM5R3.cjs.map +1 -0
  17. package/dist/chunk-JJJJTACK.js +196 -0
  18. package/dist/chunk-JJJJTACK.js.map +1 -0
  19. package/dist/chunk-LJNSJFOL.js +38 -0
  20. package/dist/chunk-LJNSJFOL.js.map +1 -0
  21. package/dist/chunk-M7MUPWCE.js +116 -0
  22. package/dist/chunk-M7MUPWCE.js.map +1 -0
  23. package/dist/chunk-PMF4GMHD.js +154 -0
  24. package/dist/chunk-PMF4GMHD.js.map +1 -0
  25. package/dist/chunk-QTRGJ2EN.cjs +2635 -0
  26. package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
  27. package/dist/chunk-RSBW2B3D.cjs +126 -0
  28. package/dist/chunk-RSBW2B3D.cjs.map +1 -0
  29. package/dist/chunk-RTFJ32T5.js +2635 -0
  30. package/dist/chunk-RTFJ32T5.js.map +1 -0
  31. package/dist/chunk-SFVEQ2T5.cjs +438 -0
  32. package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
  33. package/dist/chunk-SZT36SGB.cjs +154 -0
  34. package/dist/chunk-SZT36SGB.cjs.map +1 -0
  35. package/dist/chunk-TI24L4XE.cjs.map +1 -1
  36. package/dist/chunk-ULQXD4YZ.cjs +116 -0
  37. package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
  38. package/dist/chunk-VYHJX54R.js +126 -0
  39. package/dist/chunk-VYHJX54R.js.map +1 -0
  40. package/dist/cli/db-runner.cjs +497 -0
  41. package/dist/cli/db-runner.cjs.map +1 -0
  42. package/dist/cli/db-runner.d.cts +2 -0
  43. package/dist/cli/db-runner.d.ts +2 -0
  44. package/dist/cli/db-runner.js +497 -0
  45. package/dist/cli/db-runner.js.map +1 -0
  46. package/dist/cli/index.cjs +447 -69
  47. package/dist/cli/index.cjs.map +1 -1
  48. package/dist/cli/index.js +473 -95
  49. package/dist/cli/index.js.map +1 -1
  50. package/dist/docs/api-reference/auth.md +232 -0
  51. package/dist/docs/api-reference/compose.md +78 -0
  52. package/dist/docs/api-reference/db.md +351 -0
  53. package/dist/docs/api-reference/http-error.md +109 -0
  54. package/dist/docs/api-reference/ignite.md +323 -0
  55. package/dist/docs/api-reference/table.md +250 -0
  56. package/dist/docs/api-reference/tasks.md +140 -0
  57. package/dist/docs/cli/db.md +38 -0
  58. package/dist/docs/cli/diagnostics.md +145 -0
  59. package/dist/docs/cli/generate.md +120 -0
  60. package/dist/docs/cli/index.md +48 -0
  61. package/dist/docs/cli/start.md +112 -0
  62. package/dist/docs/contributing/index.md +139 -0
  63. package/dist/docs/core-concepts/background-tasks.md +228 -0
  64. package/dist/docs/core-concepts/clustering.md +114 -0
  65. package/dist/docs/core-concepts/file-based-routing.md +235 -0
  66. package/dist/docs/core-concepts/index.md +79 -0
  67. package/dist/docs/core-concepts/middleware.md +144 -0
  68. package/dist/docs/getting-started/index.md +91 -0
  69. package/dist/docs/getting-started/project-structure.md +154 -0
  70. package/dist/docs/guides/ai-agents.md +48 -0
  71. package/dist/docs/guides/authentication.md +196 -0
  72. package/dist/docs/guides/caching.md +124 -0
  73. package/dist/docs/guides/database.md +217 -0
  74. package/dist/docs/guides/deployment.md +171 -0
  75. package/dist/docs/guides/environment-variables.md +106 -0
  76. package/dist/docs/guides/error-handling.md +172 -0
  77. package/dist/docs/guides/generated-portals.md +115 -0
  78. package/dist/docs/guides/logging.md +70 -0
  79. package/dist/docs/guides/mailer.md +166 -0
  80. package/dist/docs/guides/migrations.md +106 -0
  81. package/dist/docs/guides/rbac.md +89 -0
  82. package/dist/docs/guides/validation.md +95 -0
  83. package/dist/docs/index.md +93 -0
  84. package/dist/docs/skills/SKILL.md +44 -0
  85. package/dist/docs/skills/api-surface.md +308 -0
  86. package/dist/docs/skills/auth-internals.md +141 -0
  87. package/dist/docs/skills/pre-flight.md +142 -0
  88. package/dist/docs/skills/routing-rules.md +114 -0
  89. package/dist/docs/skills/tasks-internals.md +172 -0
  90. package/dist/docs/skills/what-not-to-invent.md +251 -0
  91. package/dist/index.cjs +289 -391
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +472 -7
  94. package/dist/index.d.ts +472 -7
  95. package/dist/index.js +283 -385
  96. package/dist/index.js.map +1 -1
  97. package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
  98. package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
  99. package/dist/pgboss-backend-UUJOVEYK.js +14 -0
  100. package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
  101. package/dist/tasks/index.cjs.map +1 -1
  102. package/dist/tasks/index.d.cts +1 -1
  103. package/dist/tasks/index.d.ts +1 -1
  104. package/dist/types-DJCPAsM4.d.cts +541 -0
  105. package/dist/types-DJCPAsM4.d.ts +541 -0
  106. package/package.json +28 -5
  107. package/dist/chunk-6522HS2J.cjs +0 -99
  108. package/dist/chunk-6522HS2J.cjs.map +0 -1
  109. package/dist/chunk-DGVOJNR6.cjs +0 -55
  110. package/dist/chunk-DGVOJNR6.cjs.map +0 -1
  111. package/dist/chunk-KOHLLUN7.js +0 -55
  112. package/dist/chunk-KOHLLUN7.js.map +0 -1
  113. package/dist/chunk-VIP3PFWZ.js +0 -99
  114. package/dist/chunk-VIP3PFWZ.js.map +0 -1
  115. package/dist/types-BusbSenn.d.cts +0 -162
  116. package/dist/types-BusbSenn.d.ts +0 -162
@@ -0,0 +1,196 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunk7YEX4MQVcjs = require('./chunk-7YEX4MQV.cjs');
4
+
5
+
6
+
7
+ var _chunkTI24L4XEcjs = require('./chunk-TI24L4XE.cjs');
8
+
9
+
10
+ var _chunkRSBW2B3Dcjs = require('./chunk-RSBW2B3D.cjs');
11
+
12
+ // src/tasks/pgboss-backend.ts
13
+ var BOX = "__efcValue";
14
+ var box = (payload) => payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : { [BOX]: payload };
15
+ var unbox = (data) => data !== null && typeof data === "object" && BOX in data ? data[BOX] : data;
16
+ var retryOptions = (def) => ({
17
+ // pg-boss's retryLimit counts re-runs, exactly like EFC's `retries`.
18
+ retryLimit: _nullishCoalesce(def.options.retries, () => ( 3)),
19
+ retryDelay: 1,
20
+ retryBackoff: (_nullishCoalesce(def.options.backoff, () => ( "exponential"))) === "exponential"
21
+ });
22
+ async function loadPgBoss() {
23
+ try {
24
+ const mod = await Promise.resolve().then(() => _interopRequireWildcard(require("pg-boss")));
25
+ const ctor = _nullishCoalesce(mod.PgBoss, () => ( (typeof mod.default === "function" ? mod.default : mod.default.PgBoss)));
26
+ return ctor;
27
+ } catch (e) {
28
+ throw new Error("[EFC] pg-boss is not installed. Run: npm install pg-boss");
29
+ }
30
+ }
31
+ var closeImpl = null;
32
+ async function closePgBoss() {
33
+ const close = closeImpl;
34
+ closeImpl = null;
35
+ await _optionalChain([close, 'optionalCall', _2 => _2()]);
36
+ }
37
+ async function initPgBoss(opts) {
38
+ const PgBoss = await loadPgBoss();
39
+ const boss = new PgBoss({
40
+ connectionString: opts.connectionString,
41
+ ...opts.schema !== void 0 && { schema: opts.schema }
42
+ });
43
+ boss.on("error", (err) => _chunkRSBW2B3Dcjs.getLogger.call(void 0, ).error({ err }, "pg-boss error"));
44
+ await boss.start();
45
+ const queueFor = (name) => `${opts.queue}.${name}`;
46
+ const wantedSchedules = /* @__PURE__ */ new Set();
47
+ for (const def of _chunkTI24L4XEcjs.taskRegistry.values()) {
48
+ const queue = queueFor(def.name);
49
+ await boss.createQueue(queue, retryOptions(def));
50
+ await boss.work(
51
+ queue,
52
+ { localConcurrency: _nullishCoalesce(def.options.concurrency, () => ( opts.concurrency)) },
53
+ async (jobs) => {
54
+ for (const job of jobs) {
55
+ const payload = unbox(job.data);
56
+ try {
57
+ if (def.options.thread && def.filePath) await _chunk7YEX4MQVcjs.runInThread.call(void 0, def.filePath, payload);
58
+ else await def.handler(payload);
59
+ _chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info({ task: def.name, jobId: job.id }, `Task ${def.name} completed`);
60
+ } catch (err) {
61
+ _chunkRSBW2B3Dcjs.getLogger.call(void 0, ).error(
62
+ { task: def.name, jobId: job.id, attempt: job.retryCount + 1, err },
63
+ `Task ${def.name} failed`
64
+ );
65
+ throw err;
66
+ }
67
+ }
68
+ }
69
+ );
70
+ if (def.options.schedule) {
71
+ wantedSchedules.add(queue);
72
+ await boss.schedule(
73
+ queue,
74
+ def.options.schedule,
75
+ {},
76
+ {
77
+ ...retryOptions(def),
78
+ ...def.options.timezone !== void 0 && { tz: def.options.timezone }
79
+ }
80
+ );
81
+ }
82
+ }
83
+ for (const s of await boss.getSchedules()) {
84
+ if (s.name.startsWith(`${opts.queue}.`) && !wantedSchedules.has(s.name)) {
85
+ await boss.unschedule(s.name);
86
+ }
87
+ }
88
+ if (wantedSchedules.size > 0) _chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info(`Scheduled ${wantedSchedules.size} cron task(s)`);
89
+ _chunkTI24L4XEcjs.setEnqueueImpl.call(void 0, async (name, payload) => {
90
+ const def = _chunkTI24L4XEcjs.taskRegistry.get(name);
91
+ if (!def) {
92
+ throw new Error(
93
+ `[EFC] Cannot enqueue unknown task: "${name}". Is the task file in tasksDir?`
94
+ );
95
+ }
96
+ let timer;
97
+ const timeout = new Promise((_, reject) => {
98
+ timer = setTimeout(
99
+ () => reject(
100
+ new Error(
101
+ `[EFC] Cannot enqueue task "${name}": PostgreSQL did not respond within ${opts.enqueueTimeout}ms`
102
+ )
103
+ ),
104
+ opts.enqueueTimeout
105
+ );
106
+ });
107
+ try {
108
+ await Promise.race([boss.send(queueFor(name), box(payload), retryOptions(def)), timeout]);
109
+ } catch (err) {
110
+ if (err instanceof Error && err.message.startsWith("[EFC]")) throw err;
111
+ throw new Error(
112
+ `[EFC] Cannot enqueue task "${name}": ${err instanceof Error ? err.message : String(err)}`
113
+ );
114
+ } finally {
115
+ clearTimeout(timer);
116
+ }
117
+ });
118
+ closeImpl = async () => {
119
+ await boss.stop({ graceful: true, timeout: 1e4 });
120
+ };
121
+ _chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info("pg-boss backend initialised");
122
+ }
123
+ async function pgBossAdmin(connectionString, queue = "efc", schema = "pgboss") {
124
+ const PgBoss = await loadPgBoss();
125
+ const boss = new PgBoss({
126
+ connectionString,
127
+ schema,
128
+ supervise: false,
129
+ schedule: false,
130
+ migrate: false
131
+ });
132
+ boss.on("error", () => {
133
+ });
134
+ await boss.start();
135
+ const db = boss.getDb();
136
+ const prefix = `${queue}.`;
137
+ const taskOf = (name) => name.slice(prefix.length);
138
+ const table = `"${schema.replace(/"/g, '""')}".job`;
139
+ const failedRows = async (ids, limit = 1e4) => (await db.executeSql(
140
+ `SELECT id, name, data, output, retry_count, completed_on FROM ${table}
141
+ WHERE state = 'failed' AND starts_with(name, $1) ${ids.length ? "AND id = ANY($3::uuid[])" : ""}
142
+ ORDER BY completed_on DESC NULLS LAST LIMIT $2`,
143
+ ids.length ? [prefix, limit, ids] : [prefix, limit]
144
+ )).rows;
145
+ const byQueue = (rows) => {
146
+ const groups = /* @__PURE__ */ new Map();
147
+ for (const r of rows) groups.set(r.name, [..._nullishCoalesce(groups.get(r.name), () => ( [])), r.id]);
148
+ return groups;
149
+ };
150
+ return {
151
+ async counts() {
152
+ const { rows } = await db.executeSql(
153
+ `SELECT state, count(*)::int AS n FROM ${table} WHERE starts_with(name, $1) GROUP BY state`,
154
+ [prefix]
155
+ );
156
+ return Object.fromEntries(
157
+ rows.map((r) => [r.state, r.n])
158
+ );
159
+ },
160
+ async listFailed({ limit, name }) {
161
+ const rows = (await failedRows([], name ? 1e4 : limit)).filter(
162
+ (r) => !name || taskOf(r.name) === name
163
+ );
164
+ return rows.slice(0, limit).map(
165
+ (r) => ({
166
+ id: r.id,
167
+ name: taskOf(r.name),
168
+ data: unbox(r.data),
169
+ error: String(_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'access', _3 => _3.output, 'optionalAccess', _4 => _4.message]), () => ( r.output)), () => ( ""))),
170
+ attempts: r.retry_count + 1,
171
+ failedAt: _nullishCoalesce(r.completed_on, () => ( void 0))
172
+ })
173
+ );
174
+ },
175
+ async retry(ids) {
176
+ const rows = await failedRows(ids);
177
+ for (const [q, list] of byQueue(rows)) await boss.retry(q, list);
178
+ return rows.length;
179
+ },
180
+ async purge(ids) {
181
+ const rows = await failedRows(ids);
182
+ for (const [q, list] of byQueue(rows)) await boss.deleteJob(q, list);
183
+ return rows.length;
184
+ },
185
+ async close() {
186
+ await boss.stop({ graceful: false });
187
+ }
188
+ };
189
+ }
190
+
191
+
192
+
193
+
194
+
195
+ exports.closePgBoss = closePgBoss; exports.initPgBoss = initPgBoss; exports.pgBossAdmin = pgBossAdmin;
196
+ //# sourceMappingURL=chunk-47K2532L.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-47K2532L.cjs","../src/tasks/pgboss-backend.ts"],"names":[],"mappings":"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","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-47K2532L.cjs","sourcesContent":[null,"import type { PgBoss as PgBossType } from 'pg-boss';\nimport type { TaskDefinition } from '../types.js';\nimport { taskRegistry, setEnqueueImpl } from './index.js';\nimport { runInThread } from './thread-runner.js';\nimport { getLogger } from '../logger.js';\nimport type { FailedJob, TaskAdmin } from './admin.js';\n\n// pg-boss keeps one queue per job name, so each task gets its own pg-boss queue\n// named `<tasks.queue>.<TaskName>` — the prefix keeps apps sharing a database apart.\n\ninterface PgBossOpts {\n connectionString: string;\n concurrency: number;\n enqueueTimeout: number;\n queue: string;\n schema?: string;\n}\n\n// pg-boss payloads must be objects; other values are boxed so any enqueue() payload works.\nconst BOX = '__efcValue';\nconst box = (payload: unknown): object =>\n payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? (payload as object)\n : { [BOX]: payload };\nconst unbox = (data: unknown): unknown =>\n data !== null && typeof data === 'object' && BOX in data\n ? (data as Record<string, unknown>)[BOX]\n : data;\n\nconst retryOptions = (def: TaskDefinition) => ({\n // pg-boss's retryLimit counts re-runs, exactly like EFC's `retries`.\n retryLimit: def.options.retries ?? 3,\n retryDelay: 1,\n retryBackoff: (def.options.backoff ?? 'exponential') === 'exponential',\n});\n\nasync function loadPgBoss(): Promise<typeof PgBossType> {\n try {\n const mod = (await import('pg-boss')) as unknown as {\n PgBoss?: typeof PgBossType;\n default?: typeof PgBossType | { PgBoss: typeof PgBossType };\n };\n const ctor =\n mod.PgBoss ??\n (typeof mod.default === 'function'\n ? mod.default\n : (mod.default as { PgBoss: typeof PgBossType }).PgBoss);\n return ctor;\n } catch {\n throw new Error('[EFC] pg-boss is not installed. Run: npm install pg-boss');\n }\n}\n\nlet closeImpl: (() => Promise<void>) | null = null;\n\nexport async function closePgBoss(): Promise<void> {\n const close = closeImpl;\n closeImpl = null;\n await close?.();\n}\n\nexport async function initPgBoss(opts: PgBossOpts): Promise<void> {\n const PgBoss = await loadPgBoss();\n const boss = new PgBoss({\n connectionString: opts.connectionString,\n ...(opts.schema !== undefined && { schema: opts.schema }),\n });\n boss.on('error', (err: Error) => getLogger().error({ err }, 'pg-boss error'));\n await boss.start();\n\n const queueFor = (name: string) => `${opts.queue}.${name}`;\n const wantedSchedules = new Set<string>();\n\n for (const def of taskRegistry.values()) {\n const queue = queueFor(def.name);\n await boss.createQueue(queue, retryOptions(def));\n await boss.work(\n queue,\n { localConcurrency: def.options.concurrency ?? opts.concurrency },\n async (jobs: { id: string; data: unknown; retryCount: number }[]) => {\n for (const job of jobs) {\n const payload = unbox(job.data);\n try {\n if (def.options.thread && def.filePath) await runInThread(def.filePath, payload);\n else await def.handler(payload);\n getLogger().info({ task: def.name, jobId: job.id }, `Task ${def.name} completed`);\n } catch (err) {\n getLogger().error(\n { task: def.name, jobId: job.id, attempt: job.retryCount + 1, err },\n `Task ${def.name} failed`,\n );\n throw err;\n }\n }\n },\n );\n if (def.options.schedule) {\n wantedSchedules.add(queue);\n await boss.schedule(\n queue,\n def.options.schedule,\n {},\n {\n ...retryOptions(def),\n ...(def.options.timezone !== undefined && { tz: def.options.timezone }),\n },\n );\n }\n }\n\n // Drop schedules for tasks that lost their `schedule` or no longer exist.\n for (const s of await boss.getSchedules()) {\n if (s.name.startsWith(`${opts.queue}.`) && !wantedSchedules.has(s.name)) {\n await boss.unschedule(s.name);\n }\n }\n if (wantedSchedules.size > 0) getLogger().info(`Scheduled ${wantedSchedules.size} cron task(s)`);\n\n setEnqueueImpl(async (name, payload) => {\n const def = taskRegistry.get(name);\n if (!def) {\n throw new Error(\n `[EFC] Cannot enqueue unknown task: \"${name}\". Is the task file in tasksDir?`,\n );\n }\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `[EFC] Cannot enqueue task \"${name}\": PostgreSQL did not respond within ${opts.enqueueTimeout}ms`,\n ),\n ),\n opts.enqueueTimeout,\n );\n });\n try {\n await Promise.race([boss.send(queueFor(name), box(payload), retryOptions(def)), timeout]);\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[EFC]')) throw err;\n throw new Error(\n `[EFC] Cannot enqueue task \"${name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n clearTimeout(timer);\n }\n });\n\n closeImpl = async () => {\n // graceful: lets in-flight jobs finish before the connection pool closes.\n await boss.stop({ graceful: true, timeout: 10_000 });\n };\n\n getLogger().info('pg-boss backend initialised');\n}\n\n/** Dead-letter inspection for `efc tasks failed | retry | purge` on pg-boss. */\nexport async function pgBossAdmin(\n connectionString: string,\n queue = 'efc',\n schema = 'pgboss',\n): Promise<TaskAdmin> {\n const PgBoss = await loadPgBoss();\n // No supervision or cron here: this instance only reads and settles jobs.\n const boss = new PgBoss({\n connectionString,\n schema,\n supervise: false,\n schedule: false,\n migrate: false,\n });\n boss.on('error', () => {});\n await boss.start();\n const db = boss.getDb();\n const prefix = `${queue}.`;\n const taskOf = (name: string) => name.slice(prefix.length);\n const table = `\"${schema.replace(/\"/g, '\"\"')}\".job`;\n\n const failedRows = async (ids: string[], limit = 10_000) =>\n (\n await db.executeSql(\n `SELECT id, name, data, output, retry_count, completed_on FROM ${table}\n WHERE state = 'failed' AND starts_with(name, $1) ${ids.length ? 'AND id = ANY($3::uuid[])' : ''}\n ORDER BY completed_on DESC NULLS LAST LIMIT $2`,\n ids.length ? [prefix, limit, ids] : [prefix, limit],\n )\n ).rows as {\n id: string;\n name: string;\n data: unknown;\n output: unknown;\n retry_count: number;\n completed_on: Date | null;\n }[];\n\n const byQueue = (rows: { id: string; name: string }[]) => {\n const groups = new Map<string, string[]>();\n for (const r of rows) groups.set(r.name, [...(groups.get(r.name) ?? []), r.id]);\n return groups;\n };\n\n return {\n async counts() {\n const { rows } = await db.executeSql(\n `SELECT state, count(*)::int AS n FROM ${table} WHERE starts_with(name, $1) GROUP BY state`,\n [prefix],\n );\n return Object.fromEntries(\n (rows as { state: string; n: number }[]).map((r) => [r.state, r.n]),\n );\n },\n async listFailed({ limit, name }) {\n const rows = (await failedRows([], name ? 10_000 : limit)).filter(\n (r) => !name || taskOf(r.name) === name,\n );\n return rows.slice(0, limit).map(\n (r): FailedJob => ({\n id: r.id,\n name: taskOf(r.name),\n data: unbox(r.data),\n error: String((r.output as { message?: string } | null)?.message ?? r.output ?? ''),\n attempts: r.retry_count + 1,\n failedAt: r.completed_on ?? undefined,\n }),\n );\n },\n async retry(ids) {\n const rows = await failedRows(ids);\n for (const [q, list] of byQueue(rows)) await boss.retry(q, list);\n return rows.length;\n },\n async purge(ids) {\n const rows = await failedRows(ids);\n for (const [q, list] of byQueue(rows)) await boss.deleteJob(q, list);\n return rows.length;\n },\n async close() {\n await boss.stop({ graceful: false });\n },\n };\n}\n"]}
@@ -0,0 +1,438 @@
1
+ import {
2
+ parseRedisUrl
3
+ } from "./chunk-PMF4GMHD.js";
4
+ import {
5
+ notInstalled
6
+ } from "./chunk-3VWD2ZED.js";
7
+ import {
8
+ getLogger,
9
+ setCurrentUser
10
+ } from "./chunk-VYHJX54R.js";
11
+
12
+ // src/auth/index.ts
13
+ import { randomUUID as randomUUID2 } from "crypto";
14
+ import { SignJWT, jwtVerify } from "jose";
15
+
16
+ // src/cache/index.ts
17
+ import cluster2 from "cluster";
18
+
19
+ // src/cache/ipc.ts
20
+ import cluster from "cluster";
21
+ import { randomUUID } from "crypto";
22
+ var TAG = "__efcCache";
23
+ var TIMEOUT_MS = 2e3;
24
+ var isTagged = (msg) => msg !== null && typeof msg === "object" && msg[TAG] === true;
25
+ function servePrimaryCache(maxEntries) {
26
+ const store = memoryBackend(maxEntries);
27
+ cluster.on("message", (worker, msg) => {
28
+ if (!isTagged(msg)) return;
29
+ const req = msg;
30
+ const run = async () => {
31
+ switch (req.op) {
32
+ case "ping":
33
+ return "pong";
34
+ case "get":
35
+ return store.get(req.args[0]);
36
+ case "set":
37
+ return store.set(
38
+ req.args[0],
39
+ req.args[1],
40
+ req.args[2]
41
+ );
42
+ case "del":
43
+ return store.del(req.args[0]);
44
+ case "clear":
45
+ return store.clear(req.args[0]);
46
+ }
47
+ };
48
+ run().then(
49
+ (result) => worker.isConnected() && worker.send({ [TAG]: true, id: req.id, ok: true, result }),
50
+ (err) => worker.isConnected() && worker.send({ [TAG]: true, id: req.id, ok: false, error: String(err) })
51
+ );
52
+ });
53
+ }
54
+ async function connectPrimaryCache() {
55
+ if (!process.send) return null;
56
+ const pending2 = /* @__PURE__ */ new Map();
57
+ const onMessage = (msg) => {
58
+ if (!isTagged(msg)) return;
59
+ const res = msg;
60
+ const p = pending2.get(res.id);
61
+ if (!p) return;
62
+ pending2.delete(res.id);
63
+ clearTimeout(p.timer);
64
+ if (res.ok) p.resolve(res.result);
65
+ else p.reject(new Error(res.error));
66
+ };
67
+ process.on("message", onMessage);
68
+ const call = (op, ...args) => new Promise((resolve, reject) => {
69
+ const id = randomUUID();
70
+ const timer = setTimeout(() => {
71
+ pending2.delete(id);
72
+ reject(new Error(`[EFC] cache IPC "${op}" timed out`));
73
+ }, TIMEOUT_MS);
74
+ timer.unref();
75
+ pending2.set(id, { resolve, reject, timer });
76
+ process.send({ [TAG]: true, id, op, args });
77
+ });
78
+ try {
79
+ await call("ping");
80
+ } catch {
81
+ process.off("message", onMessage);
82
+ getLogger().warn(
83
+ 'cache backend "memory": no EFC cluster primary answered \u2014 using a per-worker store (entries and revoked sessions are not shared)'
84
+ );
85
+ return null;
86
+ }
87
+ return {
88
+ get: async (key) => await call("get", key),
89
+ set: async (key, value, ttl) => {
90
+ await call("set", key, value, ttl);
91
+ },
92
+ del: async (keys) => await call("del", keys),
93
+ clear: async (prefix2) => await call("clear", prefix2),
94
+ close: async () => {
95
+ process.off("message", onMessage);
96
+ for (const p of pending2.values()) clearTimeout(p.timer);
97
+ pending2.clear();
98
+ }
99
+ };
100
+ }
101
+
102
+ // src/cache/index.ts
103
+ function memoryBackend(maxEntries) {
104
+ const store = /* @__PURE__ */ new Map();
105
+ const live = (key) => {
106
+ const hit = store.get(key);
107
+ if (!hit) return void 0;
108
+ if (hit.expires !== 0 && hit.expires <= Date.now()) {
109
+ store.delete(key);
110
+ return void 0;
111
+ }
112
+ return hit;
113
+ };
114
+ return {
115
+ async get(key) {
116
+ const hit = live(key);
117
+ if (!hit) return null;
118
+ store.delete(key);
119
+ store.set(key, hit);
120
+ return hit.value;
121
+ },
122
+ async set(key, value, ttl) {
123
+ store.delete(key);
124
+ store.set(key, { value, expires: ttl ? Date.now() + ttl * 1e3 : 0 });
125
+ while (store.size > maxEntries) store.delete(store.keys().next().value);
126
+ },
127
+ async del(keys) {
128
+ let n = 0;
129
+ for (const k of keys) if (live(k) && store.delete(k)) n++;
130
+ return n;
131
+ },
132
+ async clear(prefix2) {
133
+ let n = 0;
134
+ for (const k of [...store.keys()]) if (k.startsWith(prefix2) && store.delete(k)) n++;
135
+ return n;
136
+ },
137
+ async close() {
138
+ store.clear();
139
+ }
140
+ };
141
+ }
142
+ async function redisBackend(url, timeout) {
143
+ let Redis;
144
+ try {
145
+ const mod = await import("ioredis");
146
+ Redis = mod.Redis ?? mod.default;
147
+ } catch (err) {
148
+ throw notInstalled(err, "ioredis", "npm install ioredis");
149
+ }
150
+ const client = new Redis({
151
+ ...parseRedisUrl(url),
152
+ // Fail fast instead of queueing commands while disconnected; callers treat
153
+ // a rejected command as a miss.
154
+ enableOfflineQueue: false,
155
+ maxRetriesPerRequest: 1,
156
+ commandTimeout: timeout
157
+ });
158
+ let lastWarn = 0;
159
+ client.on("error", (err) => {
160
+ if (Date.now() - lastWarn > 3e4) {
161
+ lastWarn = Date.now();
162
+ getLogger().warn(`Cache Redis unavailable: ${err.message} (serving cache misses)`);
163
+ }
164
+ });
165
+ await new Promise((resolve) => {
166
+ const timer = setTimeout(resolve, Math.max(2e3, timeout * 2));
167
+ client.once("ready", () => {
168
+ clearTimeout(timer);
169
+ resolve();
170
+ });
171
+ });
172
+ return {
173
+ get: (key) => client.get(key),
174
+ async set(key, value, ttl) {
175
+ if (ttl) await client.set(key, value, "EX", Math.max(1, Math.ceil(ttl)));
176
+ else await client.set(key, value);
177
+ },
178
+ del: (keys) => keys.length ? client.del(...keys) : Promise.resolve(0),
179
+ async clear(prefix2) {
180
+ let n = 0;
181
+ let cursor = "0";
182
+ const match = prefix2.replace(/[*?[\]\\]/g, "\\$&") + "*";
183
+ do {
184
+ const [next, keys] = await client.scan(cursor, "MATCH", match, "COUNT", 500);
185
+ cursor = next;
186
+ if (keys.length) n += await client.unlink(...keys);
187
+ } while (cursor !== "0");
188
+ return n;
189
+ },
190
+ async close() {
191
+ await client.quit().catch(() => client.disconnect());
192
+ }
193
+ };
194
+ }
195
+ var backend = null;
196
+ var prefix = "efc:";
197
+ var revocationFailure = "reject";
198
+ function revocationFailureMode() {
199
+ return revocationFailure;
200
+ }
201
+ var pending = /* @__PURE__ */ new Map();
202
+ async function configureCache(config) {
203
+ await closeCache();
204
+ prefix = config.prefix ?? "efc:";
205
+ revocationFailure = config.onRevocationCheckError ?? "reject";
206
+ if (config.backend === "redis") {
207
+ backend = await redisBackend(config.url ?? "redis://localhost:6379", config.timeout ?? 1e3);
208
+ } else if (cluster2.isWorker) {
209
+ backend = await connectPrimaryCache() ?? memoryBackend(config.maxEntries ?? 1e4);
210
+ } else {
211
+ backend = memoryBackend(config.maxEntries ?? 1e4);
212
+ }
213
+ }
214
+ function isCacheConfigured() {
215
+ return backend !== null;
216
+ }
217
+ async function closeCache() {
218
+ const b = backend;
219
+ backend = null;
220
+ pending.clear();
221
+ await b?.close();
222
+ }
223
+ function requireBackend() {
224
+ if (!backend) throw new Error("[EFC] Cache not configured \u2014 pass cache: { backend } to ignite()");
225
+ return backend;
226
+ }
227
+ async function safely(op, fn, fallback) {
228
+ const b = requireBackend();
229
+ try {
230
+ return await fn(b);
231
+ } catch (err) {
232
+ getLogger().debug({ err }, `cache ${op} failed`);
233
+ return fallback;
234
+ }
235
+ }
236
+ var cache = {
237
+ async get(key) {
238
+ const raw = await safely("get", (b) => b.get(prefix + key), null);
239
+ return raw === null ? void 0 : JSON.parse(raw);
240
+ },
241
+ async set(key, value, options) {
242
+ if (value === void 0) return;
243
+ await safely("set", (b) => b.set(prefix + key, JSON.stringify(value), options?.ttl), void 0);
244
+ },
245
+ async has(key) {
246
+ return await safely("get", (b) => b.get(prefix + key), null) !== null;
247
+ },
248
+ async del(...keys) {
249
+ return safely("del", (b) => b.del(keys.map((k) => prefix + k)), 0);
250
+ },
251
+ async wrap(key, options, fn) {
252
+ const hit = await cache.get(key);
253
+ if (hit !== void 0) return hit;
254
+ const inflight = pending.get(key);
255
+ if (inflight) return inflight;
256
+ const run = (async () => {
257
+ try {
258
+ const value = await fn();
259
+ await cache.set(key, value, typeof options === "number" ? { ttl: options } : options);
260
+ return value;
261
+ } finally {
262
+ pending.delete(key);
263
+ }
264
+ })();
265
+ pending.set(key, run);
266
+ return run;
267
+ },
268
+ async clear(keyPrefix = "") {
269
+ return safely("clear", (b) => b.clear(prefix + keyPrefix), 0);
270
+ }
271
+ };
272
+ async function rawGet(key) {
273
+ return requireBackend().get(prefix + key);
274
+ }
275
+ async function rawSet(key, value, ttlSeconds) {
276
+ await requireBackend().set(prefix + key, value, ttlSeconds);
277
+ }
278
+
279
+ // src/auth/index.ts
280
+ var _config = null;
281
+ function configureAuth(config) {
282
+ _config = config;
283
+ }
284
+ function getConfig() {
285
+ if (!_config) throw new Error("[EFC] Auth not configured \u2014 pass jwtSecret to ignite()");
286
+ return _config;
287
+ }
288
+ async function sign(payload) {
289
+ const { secret, expiresIn } = getConfig();
290
+ return new SignJWT({ ...payload, efc_iat: Date.now() }).setProtectedHeader({ alg: "HS256" }).setJti(randomUUID2()).setIssuedAt().setExpirationTime(expiresIn).sign(new TextEncoder().encode(secret));
291
+ }
292
+ async function issueToken(res, payload) {
293
+ const { cookieDomain } = getConfig();
294
+ const token = await sign(payload);
295
+ res.cookie("efc_token", token, {
296
+ httpOnly: true,
297
+ secure: process.env["NODE_ENV"] === "production",
298
+ sameSite: "strict",
299
+ ...cookieDomain !== void 0 && { domain: cookieDomain }
300
+ });
301
+ }
302
+ function revokeToken(res) {
303
+ res.clearCookie("efc_token");
304
+ }
305
+ async function signToken(payload) {
306
+ return sign(payload);
307
+ }
308
+ function tokenFrom(req) {
309
+ if (getConfig().strategy === "http-only") {
310
+ return req.cookies?.["efc_token"];
311
+ }
312
+ const auth = req.headers["authorization"];
313
+ return typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7) : void 0;
314
+ }
315
+ async function verify(token) {
316
+ const { payload } = await jwtVerify(token, new TextEncoder().encode(getConfig().secret));
317
+ return payload;
318
+ }
319
+ var userIdOf = (payload) => {
320
+ const id = payload.sub ?? payload["id"];
321
+ return id === void 0 || id === null ? void 0 : String(id);
322
+ };
323
+ function tokenLifetimeSeconds() {
324
+ const m = /^(\d+(?:\.\d+)?)\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?|d|days?|w|weeks?|y|yrs?|years?)?$/i.exec(
325
+ getConfig().expiresIn.trim()
326
+ );
327
+ if (!m) return 30 * 86400;
328
+ const n = Number(m[1]);
329
+ const unit = (m[2] ?? "s")[0].toLowerCase();
330
+ const factor = { s: 1, m: 60, h: 3600, d: 86400, w: 604800, y: 31557600 }[unit] ?? 1;
331
+ return Math.ceil(n * factor);
332
+ }
333
+ var lastRevocationError = 0;
334
+ async function isRevoked(payload) {
335
+ if (payload.jti && await rawGet(`sess:jti:${payload.jti}`) !== null) return true;
336
+ const userId = userIdOf(payload);
337
+ if (userId === void 0) return false;
338
+ const cutoff = await rawGet(`sess:user:${userId}`);
339
+ if (cutoff === null) return false;
340
+ const issuedMs = typeof payload["efc_iat"] === "number" ? payload["efc_iat"] : (payload.iat ?? 0) * 1e3;
341
+ return issuedMs < Number(cutoff);
342
+ }
343
+ function requireRevocationStore() {
344
+ if (!isCacheConfigured()) {
345
+ throw new Error(
346
+ '[EFC] Session revocation needs a cache \u2014 pass cache: { backend: "redis" } to ignite()'
347
+ );
348
+ }
349
+ }
350
+ async function revokeSession(req, res) {
351
+ requireRevocationStore();
352
+ const token = tokenFrom(req);
353
+ if (res && getConfig().strategy === "http-only") res.clearCookie("efc_token");
354
+ if (!token) return;
355
+ let payload;
356
+ try {
357
+ payload = await verify(token);
358
+ } catch {
359
+ return;
360
+ }
361
+ if (!payload.jti) return;
362
+ const ttl = payload.exp ? payload.exp - Math.floor(Date.now() / 1e3) : tokenLifetimeSeconds();
363
+ if (ttl > 0) await rawSet(`sess:jti:${payload.jti}`, "1", ttl);
364
+ }
365
+ async function revokeAllSessions(userId) {
366
+ requireRevocationStore();
367
+ await rawSet(`sess:user:${String(userId)}`, String(Date.now()), tokenLifetimeSeconds());
368
+ }
369
+ async function authenticate(req, res, next, roles) {
370
+ try {
371
+ const token = tokenFrom(req);
372
+ if (!token) {
373
+ res.status(401).json({ error: "Unauthorized" });
374
+ return;
375
+ }
376
+ const payload = await verify(token);
377
+ if (isCacheConfigured()) {
378
+ let revoked = false;
379
+ try {
380
+ revoked = await isRevoked(payload);
381
+ } catch (err) {
382
+ const reject = revocationFailureMode() === "reject";
383
+ if (Date.now() - lastRevocationError > 3e4) {
384
+ lastRevocationError = Date.now();
385
+ getLogger().error(
386
+ { err },
387
+ `Session revocation check failed \u2014 ${reject ? "rejecting with 503" : "allowing"} authenticated requests`
388
+ );
389
+ }
390
+ if (reject) {
391
+ res.status(503).json({ error: "Service Unavailable", statusCode: 503 });
392
+ return;
393
+ }
394
+ }
395
+ if (revoked) {
396
+ res.status(401).json({ error: "Unauthorized" });
397
+ return;
398
+ }
399
+ }
400
+ if (roles.length > 0) {
401
+ const role = payload["role"];
402
+ if (typeof role !== "string" || !roles.includes(role)) {
403
+ res.status(403).json({ error: "Forbidden" });
404
+ return;
405
+ }
406
+ }
407
+ req.user = payload;
408
+ setCurrentUser(payload);
409
+ next();
410
+ } catch {
411
+ res.status(401).json({ error: "Unauthorized" });
412
+ }
413
+ }
414
+ var requireAuth = ((...args) => {
415
+ if (args.length > 0 && typeof args[0] === "string") {
416
+ const roles = args;
417
+ return (req2, res2, next2) => {
418
+ void authenticate(req2, res2, next2, roles);
419
+ };
420
+ }
421
+ const [req, res, next] = args;
422
+ void authenticate(req, res, next, []);
423
+ });
424
+
425
+ export {
426
+ servePrimaryCache,
427
+ configureCache,
428
+ closeCache,
429
+ cache,
430
+ configureAuth,
431
+ issueToken,
432
+ revokeToken,
433
+ signToken,
434
+ revokeSession,
435
+ revokeAllSessions,
436
+ requireAuth
437
+ };
438
+ //# sourceMappingURL=chunk-5PDAWMGF.js.map