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.
- package/README.md +204 -52
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
EFC is an opinionated backend framework built on Express. Drop files in `src/api/` and they become routes. Every CPU core serves traffic automatically. Heavy work goes to a queue-backed task subsystem so requests stay fast.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.5.0 (Beta).** Router (incl. catch-all/optional segments and request validation), clustering, auth, structured logging, `defineModel` on MongoDB and PostgreSQL (types inferred from the schema), PostgreSQL-native `defineTable` with Prisma-style queries, BullMQ and pg-boss tasks with cron, and migrations are all implemented.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -18,6 +18,8 @@ Most Express apps grow the same way: a working prototype, then a maze of `router
|
|
|
18
18
|
| Single-threaded Node under load | Auto-detected CPU count → worker processes |
|
|
19
19
|
| Blocking work on the request path | `enqueue()` ships it to a queue; respond immediately |
|
|
20
20
|
| Wiring auth, DB, and middleware by hand | `ignite()` — one call bootstraps everything |
|
|
21
|
+
| Scattered model definitions | `defineModel()` — typed CRUD with zero ORM ceremony |
|
|
22
|
+
| Per-request user context in nested calls | `AsyncLocalStorage`-backed `getCurrentUser()` |
|
|
21
23
|
|
|
22
24
|
---
|
|
23
25
|
|
|
@@ -49,7 +51,7 @@ my-api/
|
|
|
49
51
|
│ ├── tasks/ # Background jobs
|
|
50
52
|
│ │ ├── SendEmail.ts
|
|
51
53
|
│ │ └── ResizeImage.ts
|
|
52
|
-
│ ├──
|
|
54
|
+
│ ├── model/ # Engine-agnostic models
|
|
53
55
|
│ │ └── User.ts
|
|
54
56
|
│ └── index.ts # Framework entry point
|
|
55
57
|
├── efc.config.ts
|
|
@@ -57,6 +59,8 @@ my-api/
|
|
|
57
59
|
└── .env.example
|
|
58
60
|
```
|
|
59
61
|
|
|
62
|
+
`src/api` and `src/tasks` are resolved by convention — they are **not** `ignite()` options. EFC probes `src/api`/`src/tasks`, then `<cwd>/api`/`<cwd>/tasks`, then `dist/api`/`dist/tasks`. You only need a different layout if you're doing something unusual.
|
|
63
|
+
|
|
60
64
|
Routing rules:
|
|
61
65
|
|
|
62
66
|
| File | URL |
|
|
@@ -75,7 +79,7 @@ Export uppercase HTTP method names. Anything not exported returns **405 Method N
|
|
|
75
79
|
```ts
|
|
76
80
|
// src/api/users/index.ts
|
|
77
81
|
import type { Request, Response } from 'express';
|
|
78
|
-
import { User } from '../../
|
|
82
|
+
import { User } from '../../model/User.js';
|
|
79
83
|
|
|
80
84
|
export const GET = async (req: Request, res: Response) => {
|
|
81
85
|
const users = await User.find();
|
|
@@ -91,7 +95,7 @@ export const POST = async (req: Request, res: Response) => {
|
|
|
91
95
|
```ts
|
|
92
96
|
// src/api/users/[id].ts
|
|
93
97
|
import type { Request, Response } from 'express';
|
|
94
|
-
import { User } from '../../
|
|
98
|
+
import { User } from '../../model/User.js';
|
|
95
99
|
import { HttpError } from 'express-file-cluster';
|
|
96
100
|
|
|
97
101
|
export const GET = async (req: Request, res: Response) => {
|
|
@@ -114,7 +118,6 @@ Three tiers, each with a clear scope:
|
|
|
114
118
|
|
|
115
119
|
```ts
|
|
116
120
|
// 1. Global — applies to every request
|
|
117
|
-
// CORS is built-in — configure it via CORS_ORIGINS in .env, not a separate package
|
|
118
121
|
ignite({ globalMiddlewares: [rateLimiter()] });
|
|
119
122
|
|
|
120
123
|
// 2. Route-level — applies to every handler in this file
|
|
@@ -131,6 +134,95 @@ export const POST = compose(
|
|
|
131
134
|
|
|
132
135
|
---
|
|
133
136
|
|
|
137
|
+
## Database
|
|
138
|
+
|
|
139
|
+
### `defineModel(name, schema, options?)`
|
|
140
|
+
|
|
141
|
+
Declare a typed model with a schema. EFC compiles it to a Mongoose model and wraps it in a clean CRUD surface.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// src/model/User.ts
|
|
145
|
+
import { defineModel, type InferRecord } from 'express-file-cluster';
|
|
146
|
+
|
|
147
|
+
export const User = defineModel('User', {
|
|
148
|
+
name: { type: 'string', required: true },
|
|
149
|
+
email: { type: 'string', required: true, unique: true },
|
|
150
|
+
role: { type: 'string', enum: ['admin', 'user'], default: 'user' },
|
|
151
|
+
verifyToken: { type: 'string', default: '$uuid' }, // fresh UUID per document
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// Types come from the schema — no interface to write:
|
|
155
|
+
export type User = InferRecord<typeof User>;
|
|
156
|
+
// { id: string; name: string; email: string; role: 'admin' | 'user'; verifyToken: string; createdAt: Date; ... }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Schema default operator codes
|
|
160
|
+
|
|
161
|
+
Instead of a literal or a raw function, `default` also accepts a sentinel string — resolved to a fresh per-document value at schema-compile time, never baked in once:
|
|
162
|
+
|
|
163
|
+
| Code | Resolves to |
|
|
164
|
+
|---|---|
|
|
165
|
+
| `'$now'` | `new Date()` |
|
|
166
|
+
| `'$uuid'` | `crypto.randomUUID()` |
|
|
167
|
+
| `'$objectId'` | fresh Mongoose `ObjectId` |
|
|
168
|
+
| `'$timestamp'` | `Date.now()` (number) |
|
|
169
|
+
| `'$shortId'` | random 16-char base64url string |
|
|
170
|
+
| `'$currentUser'` | full JWT payload from the in-flight request |
|
|
171
|
+
| `'$currentUser.<key>'` | single field from that payload (e.g. `'$currentUser.id'`) |
|
|
172
|
+
|
|
173
|
+
Any other value is used as-is — only these exact strings are special-cased.
|
|
174
|
+
|
|
175
|
+
### Auto-increment (`sequence`)
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
export const Order = defineModel('Order', {
|
|
179
|
+
orderNumber: { type: 'number', sequence: true, required: true },
|
|
180
|
+
// sequence: 'global.orders' — explicit key to share a counter across models
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`sequence` is a field option, not a `default` code — an auto-increment needs an async read-modify-write against a counters collection, but `default` resolves synchronously. It's assigned atomically in a `pre('validate')` hook, before `required` validation runs, so the field can be both `required: true` and auto-filled. Top-level fields only.
|
|
185
|
+
|
|
186
|
+
### Timestamps control
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
// Disable Mongoose's automatic createdAt/updatedAt (default: on)
|
|
190
|
+
export const Role = defineModel('Role', schema, {
|
|
191
|
+
timestamps: false,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// Or rename them
|
|
195
|
+
export const Audit = defineModel('Audit', schema, {
|
|
196
|
+
timestamps: { createdAt: 'created_at', updatedAt: false },
|
|
197
|
+
});
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Model API — identical on MongoDB and PostgreSQL
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
await User.find({ role: { $in: ['admin', 'editor'] }, 'address.city': 'Oslo' },
|
|
204
|
+
{ sort: { createdAt: -1 }, limit: 20, skip: 20, select: ['name'], populate: 'team' });
|
|
205
|
+
await User.findById(id); // malformed id → null
|
|
206
|
+
await User.findOne({ email: 'a@b.com' });
|
|
207
|
+
await User.create({ name: 'Alice' }); // validated (400 ModelValidationError / 409 duplicate)
|
|
208
|
+
await User.createMany([...]);
|
|
209
|
+
await User.update(id, { $inc: { logins: 1 } }); // validated too
|
|
210
|
+
await User.updateMany(filter, update); // → count
|
|
211
|
+
await User.delete(id);
|
|
212
|
+
await User.deleteMany(filter); // → count
|
|
213
|
+
await User.count(filter);
|
|
214
|
+
await User.exists(filter); // → boolean
|
|
215
|
+
await User.distinct('role', filter); // → sorted distinct values
|
|
216
|
+
await User.updateOne(filter, update); // first match, one statement → record | null
|
|
217
|
+
await User.deleteOne(filter); // → deleted record | null
|
|
218
|
+
await User.upsert(filter, create, update); // update the match, or create
|
|
219
|
+
await transaction(async () => { /* model calls here share one transaction */ });
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The engine follows `DATABASE_URL` (`mongodb://` → mongoose, `postgres://` → Drizzle; install `mongoose` or `pg drizzle-orm`). Tables and indexes are created and kept in step with the models automatically on first use (`autoSync`); `efc db sync --dry-run` shows pending changes. MongoDB-only extras: `aggregate()`, TTL indexes. `Model.raw()` returns the native mongoose model / Drizzle table.
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
134
226
|
## Background Tasks
|
|
135
227
|
|
|
136
228
|
Tasks run off the request path — respond immediately, let the queue handle the work.
|
|
@@ -175,10 +267,34 @@ Task options:
|
|
|
175
267
|
| Option | Default | Description |
|
|
176
268
|
|---|---|---|
|
|
177
269
|
| `thread` | `false` | Run in a `worker_threads` thread (CPU-bound work) |
|
|
178
|
-
| `retries` | `3` |
|
|
270
|
+
| `retries` | `3` | Re-runs after a failure (up to `retries + 1` attempts) before dead-lettering |
|
|
179
271
|
| `backoff` | `'exponential'` | Delay strategy between retries |
|
|
180
272
|
| `concurrency` | `tasks.concurrency` | Parallel jobs for this task |
|
|
181
|
-
| `schedule` | — | Cron
|
|
273
|
+
| `schedule` | — | Cron pattern for recurring runs (payload `{}`) |
|
|
274
|
+
| `timezone` | server time | IANA timezone for `schedule` |
|
|
275
|
+
|
|
276
|
+
Backends: `tasks: { backend: 'bullmq', redisUrl }` or `tasks: { backend: 'pg-boss' }` (jobs in your PostgreSQL). `enqueue()` rejects after `tasks.enqueueTimeout` (default 5 s) instead of hanging when the backend is down. Dead letters: `efc tasks failed | retry | purge`.
|
|
277
|
+
|
|
278
|
+
### PostgreSQL-native: `defineTable()`
|
|
279
|
+
|
|
280
|
+
On PostgreSQL, `defineTable` gives you Prisma's query API and SQL types on the same foundation:
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
import { defineTable } from 'express-file-cluster';
|
|
284
|
+
|
|
285
|
+
export const Order = defineTable('Order', {
|
|
286
|
+
number: { type: 'string', required: true, unique: true, maxLength: 20 }, // varchar(20)
|
|
287
|
+
total: { type: 'decimal', precision: 10, scale: 2, required: true }, // '19.99', exact
|
|
288
|
+
qty: { type: 'integer', required: true },
|
|
289
|
+
tags: { type: 'array', of: 'string', default: [] }, // text[]
|
|
290
|
+
}, { id: 'serial' });
|
|
291
|
+
|
|
292
|
+
await Order.findMany({ where: { total: { gte: '100' }, tags: { has: 'vip' } }, orderBy: { createdAt: 'desc' }, take: 20 });
|
|
293
|
+
await Order.upsert({ where: { number }, create: { number, total: '0', qty: 1 }, update: { qty: { increment: 1 } } });
|
|
294
|
+
await Order.groupBy({ by: ['qty'], _sum: { total: true } });
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
See [defineTable](https://github.com/siggold/express-file-cluster/blob/main/docs/api-reference/table.md).
|
|
182
298
|
|
|
183
299
|
---
|
|
184
300
|
|
|
@@ -215,60 +331,87 @@ export const POST = async (req, res) => {
|
|
|
215
331
|
};
|
|
216
332
|
```
|
|
217
333
|
|
|
334
|
+
### Role-gating and request context
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
// Role-gated route
|
|
338
|
+
export const middlewares = [requireAuth('admin')];
|
|
339
|
+
|
|
340
|
+
// Real logout (needs `cache` in ignite()): the token is rejected from now on.
|
|
341
|
+
import { revokeSession, revokeAllSessions } from 'express-file-cluster/auth';
|
|
342
|
+
await revokeSession(req, res); // this device
|
|
343
|
+
await revokeAllSessions(userId); // every device
|
|
344
|
+
|
|
345
|
+
// getCurrentUser() reads the same verified JWT payload from anywhere in the
|
|
346
|
+
// async call chain — not just where `req` is in scope. This is also what
|
|
347
|
+
// powers the '$currentUser' / '$currentUser.<key>' defineModel default codes.
|
|
348
|
+
import { getCurrentUser } from 'express-file-cluster/auth';
|
|
349
|
+
|
|
350
|
+
const user = getCurrentUser(); // Record<string, unknown> | undefined
|
|
351
|
+
```
|
|
352
|
+
|
|
218
353
|
---
|
|
219
354
|
|
|
220
355
|
## Bootstrapper
|
|
221
356
|
|
|
222
|
-
|
|
223
|
-
// src/index.ts
|
|
224
|
-
import { ignite } from 'express-file-cluster';
|
|
225
|
-
import path from 'path';
|
|
226
|
-
import { fileURLToPath } from 'url';
|
|
357
|
+
Every runtime value (`PORT`, `DATABASE_URL`, `JWT_SECRET`, `CORS_ORIGINS`, ...) is read from `process.env` explicitly, once, in `efc.config.ts` — `ignite()` itself never touches `process.env` (`NODE_ENV` is the sole exception).
|
|
227
358
|
|
|
228
|
-
|
|
359
|
+
```ts
|
|
360
|
+
// efc.config.ts
|
|
361
|
+
import type { EFCConfig } from 'express-file-cluster';
|
|
229
362
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
tasksDir: path.join(__dirname, 'tasks'),
|
|
363
|
+
const corsOrigins = process.env.CORS_ORIGINS
|
|
364
|
+
? process.env.CORS_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean)
|
|
365
|
+
: undefined;
|
|
234
366
|
|
|
235
|
-
|
|
367
|
+
const config: EFCConfig = {
|
|
368
|
+
port: process.env.PORT ? Number(process.env.PORT) : undefined,
|
|
236
369
|
databaseUrl: process.env.DATABASE_URL,
|
|
237
|
-
|
|
238
|
-
authStrategy: 'http-only',
|
|
239
370
|
jwtSecret: process.env.JWT_SECRET,
|
|
371
|
+
cors: corsOrigins ? { origin: corsOrigins } : true,
|
|
372
|
+
authStrategy: 'http-only',
|
|
373
|
+
tasks: { backend: 'bullmq', concurrency: 5, redisUrl: process.env.REDIS_URL },
|
|
374
|
+
};
|
|
240
375
|
|
|
241
|
-
|
|
242
|
-
|
|
376
|
+
export default config;
|
|
377
|
+
```
|
|
243
378
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
},
|
|
379
|
+
```ts
|
|
380
|
+
// src/index.ts
|
|
381
|
+
import { ignite, gracefulShutdown } from 'express-file-cluster';
|
|
382
|
+
import config from '../efc.config.js';
|
|
249
383
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
});
|
|
384
|
+
ignite({
|
|
385
|
+
...config,
|
|
386
|
+
}).then(gracefulShutdown).catch(console.error);
|
|
254
387
|
```
|
|
255
388
|
|
|
389
|
+
> Don't hardcode `cluster: true` here. `ignite()`'s own default (`NODE_ENV === 'production'`)
|
|
390
|
+
> already gives clustering in prod and a single process in dev — an explicit boolean always
|
|
391
|
+
> wins over that default, so `cluster: true` would cluster in dev too. Only pass `cluster`
|
|
392
|
+
> to force one way regardless of `NODE_ENV`.
|
|
393
|
+
|
|
256
394
|
### `ignite()` options
|
|
257
395
|
|
|
258
396
|
| Option | Type | Default | Description |
|
|
259
397
|
|---|---|---|---|
|
|
260
398
|
| `port` | `number` | `3000` | HTTP listen port |
|
|
261
|
-
| `
|
|
262
|
-
| `
|
|
263
|
-
| `
|
|
264
|
-
| `
|
|
265
|
-
| `
|
|
266
|
-
| `
|
|
267
|
-
| `
|
|
399
|
+
| `basePath` | `string` | `'/v1/api'` | URL prefix for all routes |
|
|
400
|
+
| `database` | `'mongodb' \| 'postgresql'` | auto-detected from `databaseUrl` | Database engine |
|
|
401
|
+
| `databaseUrl` | `string` | — | Connection string — not read from env automatically, pass it explicitly |
|
|
402
|
+
| `authStrategy` | `'http-only' \| 'localStorage'` | `'http-only'` | Token delivery |
|
|
403
|
+
| `jwtSecret` | `string` | — | JWT signing secret — not read from env automatically, pass it explicitly |
|
|
404
|
+
| `jwtExpiresIn` | `string` | `'7d'` | Token lifetime |
|
|
405
|
+
| `cookieDomain` | `string` | — | Cookie domain (`http-only` only) |
|
|
406
|
+
| `cluster` | `boolean` | `true` in prod, `false` in dev | Enable multi-core clustering |
|
|
268
407
|
| `workers` | `number` | `os.cpus().length` | Worker count override |
|
|
269
408
|
| `tasks` | `TaskConfig \| false` | `false` | Background task runtime |
|
|
270
|
-
| `cors` | `boolean \| CorsConfig` | `true` | CORS —
|
|
409
|
+
| `cors` | `boolean \| CorsConfig` | `true` | CORS — pass `origin` explicitly, not auto-read from env |
|
|
410
|
+
| `requestTimeout` | `number` | — | Request timeout in ms (408 on exceed) |
|
|
411
|
+
| `logging` | `LoggingConfig \| false` | pretty in dev TTY, JSON otherwise | pino logging; every request gets an `X-Request-Id` |
|
|
412
|
+
| `cache` | `CacheConfig \| false` | — | `{ backend: 'redis', url }` or `{ backend: 'memory' }` — enables `cache`, `cacheResponse()` and session revocation |
|
|
271
413
|
| `globalMiddlewares` | `RequestHandler[]` | `[]` | Applied to every route |
|
|
414
|
+
| `dashboard` | `boolean` | `true` in dev | Dev route dashboard at `/` |
|
|
272
415
|
| `onWorkerReady` | `(id) => void` | — | Called when a worker boots |
|
|
273
416
|
| `onWorkerCrash` | `(id, code) => void` | — | Called before respawn |
|
|
274
417
|
| `onError` | `ErrorRequestHandler` | built-in | Override global error handler |
|
|
@@ -279,11 +422,11 @@ ignite({
|
|
|
279
422
|
|
|
280
423
|
```bash
|
|
281
424
|
# Development
|
|
282
|
-
efc start dev # Hot-reload single process
|
|
425
|
+
efc start dev # Hot-reload single process (tsx --watch), .env re-read on every restart
|
|
283
426
|
|
|
284
427
|
# Production
|
|
285
|
-
efc build prod # Type-check +
|
|
286
|
-
efc start prod # Run dist/ with clustering enabled
|
|
428
|
+
efc build prod # Type-check + transpile src/ → dist/src/ (tsup, unbundled)
|
|
429
|
+
efc start prod # Run dist/src/index.js with clustering enabled
|
|
287
430
|
|
|
288
431
|
# Tests
|
|
289
432
|
efc run tests # Vitest (--watch, --coverage passthrough)
|
|
@@ -292,11 +435,19 @@ efc run tests # Vitest (--watch, --coverage passthrough)
|
|
|
292
435
|
efc generate route users/[id] # → src/api/users/[id].ts
|
|
293
436
|
efc generate task ProcessPayment # → src/tasks/ProcessPayment.ts
|
|
294
437
|
efc generate middleware authorize # → src/middlewares/authorize.ts
|
|
438
|
+
efc generate migration add_orders # → src/migrations/<timestamp>_add_orders.ts
|
|
439
|
+
efc generate seed demo_users # → src/seeds/demo_users.ts
|
|
440
|
+
|
|
441
|
+
# Database
|
|
442
|
+
efc db migrate | rollback | status # Migrations
|
|
443
|
+
efc db seed [name] # Seeds
|
|
444
|
+
efc db studio # Read-only browser on 127.0.0.1
|
|
295
445
|
|
|
296
446
|
# Diagnostics
|
|
297
447
|
efc routes # Print resolved route table (path → file → methods)
|
|
298
448
|
efc tasks # List registered background tasks
|
|
299
|
-
efc
|
|
449
|
+
efc tasks failed | retry | purge # Dead-letter queue
|
|
450
|
+
efc doctor # Validate project setup, package.json/tsconfig, .env vars
|
|
300
451
|
```
|
|
301
452
|
|
|
302
453
|
---
|
|
@@ -312,12 +463,13 @@ efc doctor # Validate config, env vars, DB connectivity
|
|
|
312
463
|
│ │ │
|
|
313
464
|
Worker 1 Worker 2 Worker N
|
|
314
465
|
Pre-Flight lifecycle per worker:
|
|
315
|
-
1. Connect
|
|
466
|
+
1. Connect database
|
|
316
467
|
2. Configure auth
|
|
317
|
-
3. Scan
|
|
318
|
-
4.
|
|
319
|
-
5.
|
|
320
|
-
6.
|
|
468
|
+
3. Scan tasksDir → register tasks
|
|
469
|
+
4. Start BullMQ backend
|
|
470
|
+
5. Scan apiDir → build route map
|
|
471
|
+
6. Mount routes on Express
|
|
472
|
+
7. Listen (OS round-robins connections)
|
|
321
473
|
```
|
|
322
474
|
|
|
323
475
|
CPU-bound tasks fan out further into `worker_threads` — the request loop stays unblocked at every layer.
|
|
@@ -349,14 +501,14 @@ ignite({
|
|
|
349
501
|
|
|
350
502
|
## Environment Variables
|
|
351
503
|
|
|
352
|
-
`create-efc-app` generates `.env` (gitignored, `JWT_SECRET` pre-filled) and `.env.example` (committed, documented).
|
|
504
|
+
`create-efc-app` generates `.env` (gitignored, `JWT_SECRET` pre-filled) and `.env.example` (committed, documented). EFC **does not** auto-load any of these — read them yourself in `efc.config.ts` and pass them to `ignite()`.
|
|
353
505
|
|
|
354
506
|
| Variable | Required | Description |
|
|
355
507
|
|---|---|---|
|
|
356
508
|
| `PORT` | No (default `3000`) | HTTP listen port |
|
|
357
|
-
| `NODE_ENV` | No | `development \| production \| test` |
|
|
358
|
-
| `DATABASE_URL` |
|
|
359
|
-
| `JWT_SECRET` |
|
|
509
|
+
| `NODE_ENV` | No | `development \| production \| test` — the only env var EFC reads directly |
|
|
510
|
+
| `DATABASE_URL` | If using a database | MongoDB or PostgreSQL connection string |
|
|
511
|
+
| `JWT_SECRET` | If using auth | JWT signing key — auto-generated by scaffolder |
|
|
360
512
|
| `JWT_EXPIRES_IN` | No (default `7d`) | Token lifetime |
|
|
361
513
|
| `COOKIE_DOMAIN` | No | Cookie domain for `http-only` auth |
|
|
362
514
|
| `REDIS_URL` | If using BullMQ | Redis connection for the task queue |
|
package/dist/auth/index.cjs
CHANGED
|
@@ -5,13 +5,23 @@
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
|
-
var _chunk6522HS2Jcjs = require('../chunk-6522HS2J.cjs');
|
|
9
8
|
|
|
9
|
+
var _chunkSFVEQ2T5cjs = require('../chunk-SFVEQ2T5.cjs');
|
|
10
|
+
require('../chunk-SZT36SGB.cjs');
|
|
11
|
+
require('../chunk-ALBDM5R3.cjs');
|
|
12
|
+
require('../chunk-7YEX4MQV.cjs');
|
|
13
|
+
require('../chunk-TI24L4XE.cjs');
|
|
10
14
|
|
|
11
15
|
|
|
16
|
+
var _chunkRSBW2B3Dcjs = require('../chunk-RSBW2B3D.cjs');
|
|
12
17
|
|
|
13
18
|
|
|
14
19
|
|
|
15
20
|
|
|
16
|
-
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
exports.configureAuth = _chunkSFVEQ2T5cjs.configureAuth; exports.getCurrentUser = _chunkRSBW2B3Dcjs.getCurrentUser; exports.issueToken = _chunkSFVEQ2T5cjs.issueToken; exports.requireAuth = _chunkSFVEQ2T5cjs.requireAuth; exports.revokeAllSessions = _chunkSFVEQ2T5cjs.revokeAllSessions; exports.revokeSession = _chunkSFVEQ2T5cjs.revokeSession; exports.revokeToken = _chunkSFVEQ2T5cjs.revokeToken; exports.signToken = _chunkSFVEQ2T5cjs.signToken;
|
|
17
27
|
//# sourceMappingURL=index.cjs.map
|
package/dist/auth/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/auth/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,2bAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/auth/index.cjs"}
|
package/dist/auth/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
-
import { A as AuthStrategy } from '../types-
|
|
2
|
+
import { A as AuthStrategy } from '../types-DJCPAsM4.cjs';
|
|
3
3
|
|
|
4
4
|
declare function getCurrentUser(): Record<string, unknown> | undefined;
|
|
5
5
|
|
|
@@ -13,6 +13,17 @@ declare function configureAuth(config: AuthConfig): void;
|
|
|
13
13
|
declare function issueToken(res: Response, payload: Record<string, unknown>): Promise<void>;
|
|
14
14
|
declare function revokeToken(res: Response): void;
|
|
15
15
|
declare function signToken(payload: Record<string, unknown>): Promise<string>;
|
|
16
|
+
/**
|
|
17
|
+
* Revokes the token the current request was authenticated with: `requireAuth` rejects
|
|
18
|
+
* it from now until it would have expired anyway. Pass `res` to also clear the cookie
|
|
19
|
+
* (http-only strategy). Throws if the cache is unreachable, so a failed logout is visible.
|
|
20
|
+
*/
|
|
21
|
+
declare function revokeSession(req: Request, res?: Response): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Revokes every token issued to `userId` (the JWT's `sub` or `id` claim) before now —
|
|
24
|
+
* "log out of all devices", or after a password change. Tokens issued afterwards work.
|
|
25
|
+
*/
|
|
26
|
+
declare function revokeAllSessions(userId: string | number): Promise<void>;
|
|
16
27
|
/**
|
|
17
28
|
* Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.
|
|
18
29
|
* Called with role names (`middlewares = [requireAuth('admin')]`) it
|
|
@@ -24,4 +35,4 @@ interface RequireAuth {
|
|
|
24
35
|
}
|
|
25
36
|
declare const requireAuth: RequireAuth;
|
|
26
37
|
|
|
27
|
-
export { type RequireAuth, configureAuth, getCurrentUser, issueToken, requireAuth, revokeToken, signToken };
|
|
38
|
+
export { type RequireAuth, configureAuth, getCurrentUser, issueToken, requireAuth, revokeAllSessions, revokeSession, revokeToken, signToken };
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
-
import { A as AuthStrategy } from '../types-
|
|
2
|
+
import { A as AuthStrategy } from '../types-DJCPAsM4.js';
|
|
3
3
|
|
|
4
4
|
declare function getCurrentUser(): Record<string, unknown> | undefined;
|
|
5
5
|
|
|
@@ -13,6 +13,17 @@ declare function configureAuth(config: AuthConfig): void;
|
|
|
13
13
|
declare function issueToken(res: Response, payload: Record<string, unknown>): Promise<void>;
|
|
14
14
|
declare function revokeToken(res: Response): void;
|
|
15
15
|
declare function signToken(payload: Record<string, unknown>): Promise<string>;
|
|
16
|
+
/**
|
|
17
|
+
* Revokes the token the current request was authenticated with: `requireAuth` rejects
|
|
18
|
+
* it from now until it would have expired anyway. Pass `res` to also clear the cookie
|
|
19
|
+
* (http-only strategy). Throws if the cache is unreachable, so a failed logout is visible.
|
|
20
|
+
*/
|
|
21
|
+
declare function revokeSession(req: Request, res?: Response): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Revokes every token issued to `userId` (the JWT's `sub` or `id` claim) before now —
|
|
24
|
+
* "log out of all devices", or after a password change. Tokens issued afterwards work.
|
|
25
|
+
*/
|
|
26
|
+
declare function revokeAllSessions(userId: string | number): Promise<void>;
|
|
16
27
|
/**
|
|
17
28
|
* Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.
|
|
18
29
|
* Called with role names (`middlewares = [requireAuth('admin')]`) it
|
|
@@ -24,4 +35,4 @@ interface RequireAuth {
|
|
|
24
35
|
}
|
|
25
36
|
declare const requireAuth: RequireAuth;
|
|
26
37
|
|
|
27
|
-
export { type RequireAuth, configureAuth, getCurrentUser, issueToken, requireAuth, revokeToken, signToken };
|
|
38
|
+
export { type RequireAuth, configureAuth, getCurrentUser, issueToken, requireAuth, revokeAllSessions, revokeSession, revokeToken, signToken };
|
package/dist/auth/index.js
CHANGED
|
@@ -1,16 +1,26 @@
|
|
|
1
1
|
import {
|
|
2
2
|
configureAuth,
|
|
3
|
-
getCurrentUser,
|
|
4
3
|
issueToken,
|
|
5
4
|
requireAuth,
|
|
5
|
+
revokeAllSessions,
|
|
6
|
+
revokeSession,
|
|
6
7
|
revokeToken,
|
|
7
8
|
signToken
|
|
8
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-5PDAWMGF.js";
|
|
10
|
+
import "../chunk-PMF4GMHD.js";
|
|
11
|
+
import "../chunk-3VWD2ZED.js";
|
|
12
|
+
import "../chunk-LJNSJFOL.js";
|
|
13
|
+
import "../chunk-HBYSKULC.js";
|
|
14
|
+
import {
|
|
15
|
+
getCurrentUser
|
|
16
|
+
} from "../chunk-VYHJX54R.js";
|
|
9
17
|
export {
|
|
10
18
|
configureAuth,
|
|
11
19
|
getCurrentUser,
|
|
12
20
|
issueToken,
|
|
13
21
|
requireAuth,
|
|
22
|
+
revokeAllSessions,
|
|
23
|
+
revokeSession,
|
|
14
24
|
revokeToken,
|
|
15
25
|
signToken
|
|
16
26
|
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getLogger
|
|
3
|
+
} from "./chunk-VYHJX54R.js";
|
|
4
|
+
|
|
5
|
+
// src/db/postgres.ts
|
|
6
|
+
var pool;
|
|
7
|
+
function notInstalled(err, pkg, install) {
|
|
8
|
+
const code = err.code;
|
|
9
|
+
return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`) : err;
|
|
10
|
+
}
|
|
11
|
+
var orm;
|
|
12
|
+
async function connectPostgres(url) {
|
|
13
|
+
let PoolCtor;
|
|
14
|
+
try {
|
|
15
|
+
const pg = await import("pg");
|
|
16
|
+
PoolCtor = pg.default?.Pool ?? pg.Pool;
|
|
17
|
+
} catch (err) {
|
|
18
|
+
throw notInstalled(err, "pg", "npm install pg drizzle-orm");
|
|
19
|
+
}
|
|
20
|
+
let drizzle;
|
|
21
|
+
try {
|
|
22
|
+
({ drizzle } = await import("drizzle-orm/node-postgres"));
|
|
23
|
+
} catch (err) {
|
|
24
|
+
throw notInstalled(err, "drizzle-orm", "npm install drizzle-orm");
|
|
25
|
+
}
|
|
26
|
+
const next = new PoolCtor({ connectionString: url });
|
|
27
|
+
next.on("error", (err) => getLogger().error({ err }, "PostgreSQL pool error"));
|
|
28
|
+
await next.query("select 1");
|
|
29
|
+
pool = next;
|
|
30
|
+
orm = drizzle(next);
|
|
31
|
+
getLogger().info("PostgreSQL connected");
|
|
32
|
+
return next;
|
|
33
|
+
}
|
|
34
|
+
function getOrm() {
|
|
35
|
+
if (!orm) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
"[EFC] PostgreSQL not connected \u2014 set database/databaseUrl in ignite() (or call connectPostgres)"
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return orm;
|
|
41
|
+
}
|
|
42
|
+
function getPool() {
|
|
43
|
+
if (!pool) throw new Error("[EFC] PostgreSQL not connected");
|
|
44
|
+
return pool;
|
|
45
|
+
}
|
|
46
|
+
async function closePostgres() {
|
|
47
|
+
const p = pool;
|
|
48
|
+
pool = void 0;
|
|
49
|
+
orm = void 0;
|
|
50
|
+
await p?.end();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export {
|
|
54
|
+
notInstalled,
|
|
55
|
+
connectPostgres,
|
|
56
|
+
getOrm,
|
|
57
|
+
getPool,
|
|
58
|
+
closePostgres
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=chunk-3VWD2ZED.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db/postgres.ts"],"sourcesContent":["import type { Pool } from 'pg';\nimport { getLogger } from '../logger.js';\n\n// Pre-Flight's PostgreSQL connection: a node-postgres Pool (exposed as `db`) plus a\n// Drizzle instance over it that the model adapter queries through.\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- drizzle is an optional peer, loaded dynamically */\nlet pool: Pool | undefined;\n\n/** Only a genuinely missing package becomes \"not installed\"; other load errors surface as-is. */\nexport function notInstalled(err: unknown, pkg: string, install: string): Error {\n const code = (err as { code?: string }).code;\n return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'\n ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`)\n : (err as Error);\n}\nlet orm: any;\n\nexport async function connectPostgres(url: string): Promise<Pool> {\n let PoolCtor: typeof Pool;\n try {\n const pg = (await import('pg')) as unknown as {\n default?: { Pool: typeof Pool };\n Pool?: typeof Pool;\n };\n PoolCtor = (pg.default?.Pool ?? pg.Pool)!;\n } catch (err) {\n throw notInstalled(err, 'pg', 'npm install pg drizzle-orm');\n }\n let drizzle: (client: Pool) => unknown;\n try {\n ({ drizzle } = (await import('drizzle-orm/node-postgres')) as unknown as {\n drizzle: (client: Pool) => unknown;\n });\n } catch (err) {\n throw notInstalled(err, 'drizzle-orm', 'npm install drizzle-orm');\n }\n\n const next = new PoolCtor({ connectionString: url });\n // Idle-client errors (e.g. the server restarting) are emitted on the pool; unhandled\n // they would crash the process.\n next.on('error', (err) => getLogger().error({ err }, 'PostgreSQL pool error'));\n await next.query('select 1');\n pool = next;\n orm = drizzle(next);\n getLogger().info('PostgreSQL connected');\n return next;\n}\n\nexport function getOrm(): any {\n if (!orm) {\n throw new Error(\n '[EFC] PostgreSQL not connected — set database/databaseUrl in ignite() (or call connectPostgres)',\n );\n }\n return orm;\n}\n\nexport function getPool(): Pool {\n if (!pool) throw new Error('[EFC] PostgreSQL not connected');\n return pool;\n}\n\nexport async function closePostgres(): Promise<void> {\n const p = pool;\n pool = undefined;\n orm = undefined;\n await p?.end();\n}\n"],"mappings":";;;;;AAOA,IAAI;AAGG,SAAS,aAAa,KAAc,KAAa,SAAwB;AAC9E,QAAM,OAAQ,IAA0B;AACxC,SAAO,SAAS,0BAA0B,SAAS,qBAC/C,IAAI,MAAM,SAAS,GAAG,2BAA2B,OAAO,EAAE,IACzD;AACP;AACA,IAAI;AAEJ,eAAsB,gBAAgB,KAA4B;AAChE,MAAI;AACJ,MAAI;AACF,UAAM,KAAM,MAAM,OAAO,IAAI;AAI7B,eAAY,GAAG,SAAS,QAAQ,GAAG;AAAA,EACrC,SAAS,KAAK;AACZ,UAAM,aAAa,KAAK,MAAM,4BAA4B;AAAA,EAC5D;AACA,MAAI;AACJ,MAAI;AACF,KAAC,EAAE,QAAQ,IAAK,MAAM,OAAO,2BAA2B;AAAA,EAG1D,SAAS,KAAK;AACZ,UAAM,aAAa,KAAK,eAAe,yBAAyB;AAAA,EAClE;AAEA,QAAM,OAAO,IAAI,SAAS,EAAE,kBAAkB,IAAI,CAAC;AAGnD,OAAK,GAAG,SAAS,CAAC,QAAQ,UAAU,EAAE,MAAM,EAAE,IAAI,GAAG,uBAAuB,CAAC;AAC7E,QAAM,KAAK,MAAM,UAAU;AAC3B,SAAO;AACP,QAAM,QAAQ,IAAI;AAClB,YAAU,EAAE,KAAK,sBAAsB;AACvC,SAAO;AACT;AAEO,SAAS,SAAc;AAC5B,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,UAAgB;AAC9B,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,gCAAgC;AAC3D,SAAO;AACT;AAEA,eAAsB,gBAA+B;AACnD,QAAM,IAAI;AACV,SAAO;AACP,QAAM;AACN,QAAM,GAAG,IAAI;AACf;","names":[]}
|