express-file-cluster 0.10.2 → 0.11.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 (86) hide show
  1. package/dist/auth/index.cjs +4 -4
  2. package/dist/auth/index.d.cts +3 -1
  3. package/dist/auth/index.d.ts +3 -1
  4. package/dist/auth/index.js +3 -3
  5. package/dist/{chunk-V73R76I4.js → chunk-2IDRC7RK.js} +2 -1
  6. package/dist/{chunk-RETV3GKE.js → chunk-336IU55W.js} +2 -2
  7. package/dist/{chunk-7BC3AN7R.cjs → chunk-6WTMRZS7.cjs} +8 -8
  8. package/dist/{chunk-7BC3AN7R.cjs.map → chunk-6WTMRZS7.cjs.map} +1 -1
  9. package/dist/chunk-DGYPIIJE.cjs +845 -0
  10. package/dist/chunk-DGYPIIJE.cjs.map +1 -0
  11. package/dist/{chunk-TBIVIR6L.cjs → chunk-DTMDJGRW.cjs} +8 -8
  12. package/dist/{chunk-TBIVIR6L.cjs.map → chunk-DTMDJGRW.cjs.map} +1 -1
  13. package/dist/{chunk-MUVO7MGS.js → chunk-EJDZZ4KX.js} +2 -2
  14. package/dist/{chunk-IUZ6A7PB.cjs → chunk-GWMW6XY7.cjs} +13 -13
  15. package/dist/{chunk-IUZ6A7PB.cjs.map → chunk-GWMW6XY7.cjs.map} +1 -1
  16. package/dist/{chunk-Y4NKIXUL.cjs → chunk-IEF6AEK3.cjs} +13 -13
  17. package/dist/{chunk-Y4NKIXUL.cjs.map → chunk-IEF6AEK3.cjs.map} +1 -1
  18. package/dist/{chunk-BG4A7Z32.js → chunk-JBOMTZT5.js} +3 -3
  19. package/dist/chunk-LECHRAU3.js +845 -0
  20. package/dist/chunk-LECHRAU3.js.map +1 -0
  21. package/dist/{chunk-5LPRKZPB.js → chunk-O2E7H2XA.js} +2 -2
  22. package/dist/{chunk-C2FOZ7ME.js → chunk-OM2XJJWX.js} +2 -2
  23. package/dist/{chunk-JP36TLL4.cjs → chunk-QSIP7YLW.cjs} +3 -2
  24. package/dist/chunk-QSIP7YLW.cjs.map +1 -0
  25. package/dist/{chunk-Y75V5FCU.js → chunk-R6GPQZLI.js} +3 -3
  26. package/dist/{chunk-R2K7AFIB.cjs → chunk-SOU3PBJC.cjs} +89 -89
  27. package/dist/{chunk-R2K7AFIB.cjs.map → chunk-SOU3PBJC.cjs.map} +1 -1
  28. package/dist/{chunk-4GHK27JA.cjs → chunk-WHBSVYUY.cjs} +3 -3
  29. package/dist/{chunk-4GHK27JA.cjs.map → chunk-WHBSVYUY.cjs.map} +1 -1
  30. package/dist/cli/db-runner.cjs +24 -24
  31. package/dist/cli/db-runner.js +3 -3
  32. package/dist/cli/index.cjs +8 -8
  33. package/dist/cli/index.js +5 -5
  34. package/dist/docs/api-reference/ignite.md +4 -0
  35. package/dist/docs/api-reference/openapi.md +36 -0
  36. package/dist/docs/api-reference/testing.md +2 -0
  37. package/dist/docs/api-reference/websockets.md +23 -0
  38. package/dist/docs/cli/add.md +1 -1
  39. package/dist/docs/core-concepts/clustering.md +2 -0
  40. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  41. package/dist/docs/guides/feature-matrix.md +9 -0
  42. package/dist/docs/guides/openapi.md +57 -0
  43. package/dist/docs/guides/validation.md +2 -0
  44. package/dist/docs/guides/websockets.md +60 -0
  45. package/dist/docs/index.md +3 -1
  46. package/dist/docs/skills/SKILL.md +4 -2
  47. package/dist/docs/skills/api-surface.md +10 -0
  48. package/dist/docs/skills/pre-flight.md +2 -0
  49. package/dist/docs/skills/routing-rules.md +4 -0
  50. package/dist/docs/skills/what-not-to-invent.md +2 -0
  51. package/dist/index.cjs +75 -53
  52. package/dist/index.cjs.map +1 -1
  53. package/dist/index.d.cts +3 -2
  54. package/dist/index.d.ts +3 -2
  55. package/dist/index.js +32 -11
  56. package/dist/index.js.map +1 -1
  57. package/dist/openapi-cjs.cjs +5 -0
  58. package/dist/{pgboss-backend-4X2YT4RB.js → pgboss-backend-PQW6I3VF.js} +3 -3
  59. package/dist/pgboss-backend-QVXISTLP.cjs +15 -0
  60. package/dist/{pgboss-backend-UXQ3O2WT.cjs.map → pgboss-backend-QVXISTLP.cjs.map} +1 -1
  61. package/dist/registry/index.json +1 -1
  62. package/dist/tasks/index.d.cts +3 -1
  63. package/dist/tasks/index.d.ts +3 -1
  64. package/dist/testing.cjs +16 -10
  65. package/dist/testing.cjs.map +1 -1
  66. package/dist/testing.d.cts +4 -1
  67. package/dist/testing.d.ts +4 -1
  68. package/dist/testing.js +12 -6
  69. package/dist/testing.js.map +1 -1
  70. package/dist/{types-CPMFTVXm.d.cts → types-D3QmZgeX.d.cts} +80 -2
  71. package/dist/{types-CPMFTVXm.d.ts → types-D3QmZgeX.d.ts} +80 -2
  72. package/package.json +6 -4
  73. package/dist/chunk-74BSJXWD.cjs +0 -220
  74. package/dist/chunk-74BSJXWD.cjs.map +0 -1
  75. package/dist/chunk-JP36TLL4.cjs.map +0 -1
  76. package/dist/chunk-KLWL7XSC.js +0 -220
  77. package/dist/chunk-KLWL7XSC.js.map +0 -1
  78. package/dist/pgboss-backend-UXQ3O2WT.cjs +0 -15
  79. /package/dist/{chunk-V73R76I4.js.map → chunk-2IDRC7RK.js.map} +0 -0
  80. /package/dist/{chunk-RETV3GKE.js.map → chunk-336IU55W.js.map} +0 -0
  81. /package/dist/{chunk-MUVO7MGS.js.map → chunk-EJDZZ4KX.js.map} +0 -0
  82. /package/dist/{chunk-BG4A7Z32.js.map → chunk-JBOMTZT5.js.map} +0 -0
  83. /package/dist/{chunk-5LPRKZPB.js.map → chunk-O2E7H2XA.js.map} +0 -0
  84. /package/dist/{chunk-C2FOZ7ME.js.map → chunk-OM2XJJWX.js.map} +0 -0
  85. /package/dist/{chunk-Y75V5FCU.js.map → chunk-R6GPQZLI.js.map} +0 -0
  86. /package/dist/{pgboss-backend-4X2YT4RB.js.map → pgboss-backend-PQW6I3VF.js.map} +0 -0
@@ -2,7 +2,7 @@
2
2
 
3
3
  **express-file-cluster (EFC)** is an opinionated backend framework built on Express. It removes routing ceremony, saturates every CPU core automatically, and ships a production-grade background-task subsystem — all from a single `ignite()` call.
4
4
 
5
- > **Status: v0.10.2 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
5
+ > **Status: v0.11.0 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
6
6
 
7
7
  ---
8
8
 
@@ -48,6 +48,8 @@
48
48
  | [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
49
49
  | [Coming from mongoose](./guides/coming-from-mongoose.md) | `defineCollection` for mongoose users: schema and query mapping |
50
50
  | [Testing](./guides/testing.md) | `createTestApp` for real file-based routes without service boot |
51
+ | [OpenAPI (since 0.11.0)](./guides/openapi.md) | Opt-in OpenAPI JSON from route metadata and request schemas |
52
+ | [WebSockets (since 0.11.0)](./guides/websockets.md) | WS file exports, middleware/auth, limits and shutdown |
51
53
  | [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
52
54
  | [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
53
55
  | [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |
@@ -37,12 +37,14 @@ Load **only** the module the work points to. Each is self-contained.
37
37
  docs/ ← full documentation
38
38
  ```
39
39
 
40
- ## Status (v0.10.2 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
40
+ ## Status (v0.11.0 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
41
41
 
42
42
  Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only cookie + Bearer token auth (scrypt password hashing built in), structured logging (pino, request IDs), `defineModel` on MongoDB (mongoose) **and** PostgreSQL (Drizzle) with validation, query options, bulk ops, transactions, `sync()`/`drop()`, PostgreSQL-native `defineTable` (Prisma-style queries, foreign keys, many-to-many, `include`, relation filters, nested writes), MongoDB-native `defineCollection` (mongoose vocabulary, BSON types, geo/text, `bulkWrite`, change streams), query logging (`logging.queries`), BullMQ **and** pg-boss task backends with cron schedules and dead-letter CLI, worker_threads for CPU-bound tasks, migrations/seeds/studio (`efc db`) incl. migrations generated from model diffs (`efc db generate`), `efc db pull` and `efc import-prisma`, full CLI.
43
43
 
44
- **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`.
44
+ **Not yet implemented (Phase 3+):** plugins, OpenTelemetry, `efc lint`, `efc deploy`.
45
45
 
46
46
  Phase 3 testing utilities: `createTestApp` from `express-file-cluster/testing` mounts a real route tree without service boot or a listener. Read `docs/guides/testing.md` and `docs/api-reference/testing.md`; see process-wide auth/logging isolation limits.
47
47
 
48
48
  M6 completed 2026-10-30: query logging + bounded opt-in query metrics, editable studio, pool settings + bounded prepared statements, and a strict 10% nightly benchmark gate. See `bench/results/m6-validation.md` for measured evidence. OpenTelemetry is a separate Phase 3 task.
49
+
50
+ Since 0.11.0: OpenAPI 3.1 generation (`generateOpenAPI`, `ignite({ openapi })`) and file `WS` exports with HTTP middleware/auth, origin/payload limits, heartbeat and drain. Read `docs/guides/openapi.md`, `docs/api-reference/openapi.md`, `docs/guides/websockets.md`, `docs/api-reference/websockets.md`. These APIs are available since 0.11.0.
@@ -346,3 +346,13 @@ Generated app 2FA (not core exports): TOTP/email OTP enrollment, password+code l
346
346
  Auth payloads may include `efc_auth_at` (epoch milliseconds from before credentials are read): revocation checks it conservatively against the account cutoff, capped at the server's issue time. Generated login/refresh routes set it. `/testing` supports CommonJS callers through an async bridge to its ESM implementation.
347
347
 
348
348
  ESM/CJS auth configuration, request context and cache state are shared within the process, including mixed-module middleware in `/testing`. Generated reset-password uses atomic unexpired-token consumption and clears refresh credentials; custom auth logout propagates revocation failure.
349
+
350
+ ## 0.11.0 — OpenAPI and WebSockets
351
+
352
+ Main exports: `generateOpenAPI(routes: MountedRoute[] | string, options?: OpenAPIOptions & { basePath?: string }): Promise<OpenAPIDocument>`, `attachWebSockets(server: http.Server, app: express.Express, options?: WebSocketOptions): ws.WebSocketServer`, `closeWebSockets(server: http.Server, timeoutMs = 1000): Promise<void>`. Types: `JSONSchema`, `OpenAPIOptions`, `OpenAPIDocument`, `WebSocketHandler`, `WebSocketOptions`. No new import paths.
353
+
354
+ `EFCConfig.openapi?: boolean | OpenAPIOptions` (off; default path `/openapi.json`); `EFCConfig.websocket?: false | WebSocketOptions` (auto-attach for WS exports). `TestAppOptions.openapi` matches. `MountedRoute` includes optional `schema` and `websocket`. `RouteMethodMeta` adds `summary`, `tags`, `operationId`, `openapi` operation overrides (`hidden` omits). OpenAPI uses Standard JSON Schema input or explicit `schemaToJSONSchema`, not validator source inspection. WS signature `(socket, request) => void | Promise<void>`; file/global middleware and `schema.WS` apply before upgrade. See the API references for defaults and lifecycle.
355
+
356
+ 0.11.0 review fixes: WS payload/timer options are bounded to signed int32 (payload/handshake ≥1, heartbeat ≥0). Drain destroys pending upgrades immediately; pipelined upgrades behind active HTTP responses close safely. OpenAPI URL collision checks include hidden GET/HEAD and actual Express matches. Object query fields use deepObject; object unions/intersections retain fields/requirements and `x-efc-query-schema` preserves the whole query contract. Non-object parameter shapes need explicit operation parameters. Equivalent optional paths keep the first parameter binding; conflicting templates across routes throw.
357
+
358
+ OpenAPI follow-up: array query wire names use brackets (`tags[]`, form/explode) to preserve single items; Express still exposes `req.query.tags`. External field refs are kept without fetching; local type hints or explicit parameters control their serialization. Body requiredness checks converted-schema acceptance of Express’s missing-body `{}` without calling validators; unknown refs remain required and explicit requestBody metadata overrides it.
@@ -146,3 +146,5 @@ const clusterEnabled = config.cluster ?? (process.env['NODE_ENV'] === 'productio
146
146
  `databasePool.preparedStatements?: boolean | { max?: number }` defaults true/100 names per physical connection; false or max 0 disables (Mongo ignores). A private Pool/client proxy is passed to Drizzle, preserving Pool identity and transaction-client release; exported native `db` is unchanged. Object query configs for single SELECT/INSERT/UPDATE/DELETE/WITH statements get a SQL-shape hash name; parameters/types/rowMode are untouched, explicit names/control/DDL/multi-statements unchanged. Lifetime budget bounds server names, with unnamed fallback (no eviction/DEALLOCATE). Schema sync/drop bumps generation; connection budgets never reset. External DDL requires reconnecting, and incompatible poolers require opting out. `prepared-statements.integration.test.ts` proves reuse, transactions, budget/disable and schema invalidation.
147
147
 
148
148
  `logging.queries.metrics: true | { maxEntries }` enables bounded per-process model/op aggregates (default off; enabled default 1000, zero disables). Main exports `getQueryMetrics`, `resetQueryMetrics`, `QueryMetric`, `QueryMetricsSnapshot`. Snapshots contain counters/latency summaries, since and dropped observations; no SQL/params/error details. Nested statement counts inclusive; reset/reconfigure starts a new window. Not distributed tracing.
149
+
150
+ Since 0.11.0: after route mounting metadata is loaded, optional OpenAPI is generated/served before attaching the API router. The HTTP server is explicitly created, WS upgrades attach when a WS export exists, then it listens. Graceful shutdown drains WS sockets before completing backend shutdown. Origin policy is separate from CORS; middleware/auth runs during upgrade.
@@ -112,3 +112,7 @@ Files that do NOT match this pattern are silently ignored by `scanDir`.
112
112
  Header: `Allow: GET, POST` (only the implemented methods).
113
113
 
114
114
  **Only sent when at least one method IS implemented.** A file that exports no HTTP methods gets no 405 handler — Express would return 404.
115
+
116
+ Since 0.11.0, `WS` exports mount upgrade-only handlers on the same paths; HTTP methods skip upgrade requests. File/global middleware and named params apply, then `schema.WS` validation, then the connection handler. OpenAPI documents HTTP exports only; optional path segments expand into separate required-path variants.
117
+
118
+ OpenAPI optional variants deduplicate equivalent template shapes using greedy earlier-parameter bindings; conflicting names across separate routes fail generation. Document URL collision checks use actual Express GET/HEAD matchers, including hidden routes. Query object combinators retain fields and requirements; object query fields serialize as deepObject. WS drain destroys pending handshakes; pipelined upgrades behind an active HTTP response close safely.
@@ -275,3 +275,5 @@ const conn = db.model('User') // throws: db not ready
275
275
  // ❌ With autoSync: false, using a model before `efc db sync` / a migration created its table
276
276
  // → "[EFC] <Model>: table "<t>" does not exist — autoSync is off…"
277
277
  ```
278
+
279
+ Since 0.11.0, WebSockets and OpenAPI are implemented. Read the new guides/API references before using them. Use `WS` file exports and `ignite({openapi})`/`generateOpenAPI`, with the four existing import paths only. No Socket.IO protocol, cross-worker broadcast bus, message-schema validator, Swagger UI, or automatic auth-policy inference is provided.
package/dist/index.cjs CHANGED
@@ -2,38 +2,42 @@
2
2
 
3
3
 
4
4
 
5
- var _chunk74BSJXWDcjs = require('./chunk-74BSJXWD.cjs');
6
5
 
7
6
 
8
7
 
9
8
 
9
+ var _chunkDGYPIIJEcjs = require('./chunk-DGYPIIJE.cjs');
10
10
 
11
11
 
12
12
 
13
13
 
14
- var _chunkY4NKIXULcjs = require('./chunk-Y4NKIXUL.cjs');
15
14
 
16
15
 
17
- var _chunk4GHK27JAcjs = require('./chunk-4GHK27JA.cjs');
18
16
 
19
17
 
18
+ var _chunkIEF6AEK3cjs = require('./chunk-IEF6AEK3.cjs');
20
19
 
21
- var _chunkTBIVIR6Lcjs = require('./chunk-TBIVIR6L.cjs');
22
20
 
21
+ var _chunkWHBSVYUYcjs = require('./chunk-WHBSVYUY.cjs');
23
22
 
24
23
 
25
24
 
25
+ var _chunkDTMDJGRWcjs = require('./chunk-DTMDJGRW.cjs');
26
26
 
27
27
 
28
28
 
29
29
 
30
30
 
31
- var _chunkR2K7AFIBcjs = require('./chunk-R2K7AFIB.cjs');
32
31
 
33
32
 
34
33
 
35
34
 
36
- var _chunkIUZ6A7PBcjs = require('./chunk-IUZ6A7PB.cjs');
35
+ var _chunkSOU3PBJCcjs = require('./chunk-SOU3PBJC.cjs');
36
+
37
+
38
+
39
+
40
+ var _chunkGWMW6XY7cjs = require('./chunk-GWMW6XY7.cjs');
37
41
 
38
42
 
39
43
 
@@ -41,7 +45,7 @@ var _chunkAGOYTFROcjs = require('./chunk-AGOYTFRO.cjs');
41
45
 
42
46
 
43
47
 
44
- var _chunk7BC3AN7Rcjs = require('./chunk-7BC3AN7R.cjs');
48
+ var _chunk6WTMRZS7cjs = require('./chunk-6WTMRZS7.cjs');
45
49
  require('./chunk-RPL2IFWK.cjs');
46
50
 
47
51
 
@@ -57,10 +61,11 @@ var _chunkH2PVWCWCcjs = require('./chunk-H2PVWCWC.cjs');
57
61
 
58
62
 
59
63
 
60
- var _chunkJP36TLL4cjs = require('./chunk-JP36TLL4.cjs');
64
+ var _chunkQSIP7YLWcjs = require('./chunk-QSIP7YLW.cjs');
61
65
  require('./chunk-CGY7JU4Y.cjs');
62
66
 
63
67
  // src/index.ts
68
+ var _http = require('http'); var _http2 = _interopRequireDefault(_http);
64
69
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
65
70
  var _express = require('express'); var _express2 = _interopRequireDefault(_express);
66
71
  var _cluster = require('cluster'); var _cluster2 = _interopRequireDefault(_cluster);
@@ -75,7 +80,7 @@ function workerCount() {
75
80
  }
76
81
  function shutdownMaster() {
77
82
  isShuttingDown = true;
78
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
83
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
79
84
  if (workerCount() === 0) process.exit(0);
80
85
  for (const worker of Object.values(_nullishCoalesce(_cluster2.default.workers, () => ( {})))) {
81
86
  _optionalChain([worker, 'optionalAccess', _ => _.process, 'access', _2 => _2.kill, 'call', _3 => _3("SIGTERM")]);
@@ -83,7 +88,7 @@ function shutdownMaster() {
83
88
  }
84
89
  function runMaster(options = {}) {
85
90
  const count = _nullishCoalesce(options.workers, () => ( 1));
86
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info(`Primary ${process.pid} starting ${count} workers`);
91
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Primary ${process.pid} starting ${count} workers`);
87
92
  for (let i = 0; i < count; i++) {
88
93
  _cluster2.default.fork();
89
94
  }
@@ -93,14 +98,14 @@ function runMaster(options = {}) {
93
98
  _cluster2.default.on("exit", (worker, code, signal) => {
94
99
  const exitCode = _nullishCoalesce(code, () => ( (signal ? -1 : 0)));
95
100
  if (isShuttingDown) {
96
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info(`Worker ${worker.id} gracefully exited`);
101
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Worker ${worker.id} gracefully exited`);
97
102
  if (workerCount() === 0) {
98
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info("All workers exited. Primary exiting.");
103
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info("All workers exited. Primary exiting.");
99
104
  process.exit(0);
100
105
  }
101
106
  return;
102
107
  }
103
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
108
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
104
109
  _optionalChain([options, 'access', _6 => _6.onWorkerCrash, 'optionalCall', _7 => _7(worker.id, exitCode)]);
105
110
  _cluster2.default.fork();
106
111
  });
@@ -119,13 +124,13 @@ async function scanTasks(tasksDir) {
119
124
  const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(filePath)));
120
125
  const def = mod["default"];
121
126
  if (!def || typeof def.handler !== "function") {
122
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).warn(`Task file ${file} has no valid default export \u2014 skipping`);
127
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(`Task file ${file} has no valid default export \u2014 skipping`);
123
128
  continue;
124
129
  }
125
130
  _chunkH2PVWCWCcjs.registerTask.call(void 0, taskName, { ...def, filePath });
126
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).debug(`Registered task: ${taskName}`);
131
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).debug(`Registered task: ${taskName}`);
127
132
  } catch (err) {
128
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).warn({ err }, `Failed to load task ${file}`);
133
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn({ err }, `Failed to load task ${file}`);
129
134
  }
130
135
  }
131
136
  }
@@ -150,7 +155,7 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
150
155
  const safeRoutes = JSON.stringify(
151
156
  routes.map((r) => ({
152
157
  urlPath: r.urlPath,
153
- methods: r.methods,
158
+ methods: r.websocket ? [...r.methods, "WS"] : r.methods,
154
159
  params: r.params,
155
160
  meta: _nullishCoalesce(r.meta, () => ( null))
156
161
  }))
@@ -752,7 +757,7 @@ function rateLimit(options) {
752
757
  void (async () => {
753
758
  const who = keyOf(req);
754
759
  if (who === void 0) return next();
755
- if (!_chunkY4NKIXULcjs.isCacheConfigured.call(void 0, )) {
760
+ if (!_chunkIEF6AEK3cjs.isCacheConfigured.call(void 0, )) {
756
761
  throw new Error("[EFC] rateLimit needs a cache \u2014 pass cache: { backend } to ignite()");
757
762
  }
758
763
  const bucket = _nullishCoalesce(options.name, () => ( req.baseUrl + (_nullishCoalesce(_optionalChain([req, 'access', _8 => _8.route, 'optionalAccess', _9 => _9.path]), () => ( req.path)))));
@@ -762,11 +767,11 @@ function rateLimit(options) {
762
767
  const resetMs = (slot + 1) * windowMs - now;
763
768
  let count;
764
769
  try {
765
- count = (await _chunkY4NKIXULcjs.rawIncr.call(void 0, `rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1e3) + 1)).value;
770
+ count = (await _chunkIEF6AEK3cjs.rawIncr.call(void 0, `rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1e3) + 1)).value;
766
771
  } catch (err) {
767
772
  if (Date.now() - lastCacheError > 3e4) {
768
773
  lastCacheError = Date.now();
769
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).error(
774
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error(
770
775
  { err },
771
776
  `rateLimit: cache unavailable \u2014 ${options.onCacheError === "reject" ? "rejecting with 503" : "allowing requests"}`
772
777
  );
@@ -801,14 +806,14 @@ function cacheResponse(options) {
801
806
  if (req.method !== "GET" && req.method !== "HEAD") return next();
802
807
  let scope = "";
803
808
  if (opts.perUser) {
804
- const user = _chunkJP36TLL4cjs.getCurrentUser.call(void 0, );
809
+ const user = _chunkQSIP7YLWcjs.getCurrentUser.call(void 0, );
805
810
  const id = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _10 => _10["sub"]]), () => ( _optionalChain([user, 'optionalAccess', _11 => _11["id"]])));
806
811
  if (id === void 0) return next();
807
812
  scope = `u:${String(id)}:`;
808
813
  }
809
814
  const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
810
815
  void (async () => {
811
- const hit = await _chunkY4NKIXULcjs.cache.get(key);
816
+ const hit = await _chunkIEF6AEK3cjs.cache.get(key);
812
817
  if (hit) {
813
818
  res.setHeader("X-Cache", "HIT");
814
819
  res.status(hit.status).json(hit.body);
@@ -817,7 +822,7 @@ function cacheResponse(options) {
817
822
  res.setHeader("X-Cache", "MISS");
818
823
  const json = res.json.bind(res);
819
824
  res.json = (body) => {
820
- if (res.statusCode === 200) void _chunkY4NKIXULcjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
825
+ if (res.statusCode === 200) void _chunkIEF6AEK3cjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
821
826
  return json(body);
822
827
  };
823
828
  next();
@@ -886,21 +891,21 @@ async function ignite(config) {
886
891
  const jwtSecret = config.jwtSecret;
887
892
  const authStrategy = _nullishCoalesce(config.authStrategy, () => ( "http-only"));
888
893
  const clusterEnabled = _nullishCoalesce(config.cluster, () => ( process.env["NODE_ENV"] === "production"));
889
- _chunkJP36TLL4cjs.configureLogger.call(void 0, config.logging);
894
+ _chunkQSIP7YLWcjs.configureLogger.call(void 0, config.logging);
890
895
  if (!["http-only", "bearer", "localStorage"].includes(authStrategy) && (!clusterEnabled || _cluster2.default.isPrimary)) {
891
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).warn(
896
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(
892
897
  `[EFC] Unknown authStrategy "${String(authStrategy)}" \u2014 treated as 'bearer'. Use 'http-only' or 'bearer'; this will be an error in 1.0.`
893
898
  );
894
899
  }
895
900
  if (jwtSecret && Buffer.byteLength(jwtSecret) < 32 && process.env["NODE_ENV"] === "production" && (!clusterEnabled || _cluster2.default.isPrimary)) {
896
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).warn(
901
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(
897
902
  `[EFC] jwtSecret is ${Buffer.byteLength(jwtSecret)} bytes \u2014 use at least 32 random bytes in production (openssl rand -hex 64).`
898
903
  );
899
904
  }
900
- _chunkJP36TLL4cjs.configureQueryLog.call(void 0, config.logging);
905
+ _chunkQSIP7YLWcjs.configureQueryLog.call(void 0, config.logging);
901
906
  if (clusterEnabled && _cluster2.default.isPrimary) {
902
907
  if (config.cache && config.cache.backend === "memory") {
903
- _chunkY4NKIXULcjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
908
+ _chunkIEF6AEK3cjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
904
909
  }
905
910
  runMaster({
906
911
  workers: _nullishCoalesce(workers, () => ( _os2.default.cpus().length)),
@@ -909,35 +914,35 @@ async function ignite(config) {
909
914
  });
910
915
  return;
911
916
  }
912
- const app = _chunk74BSJXWDcjs.createHttpApp.call(void 0, config);
913
- if (database) _chunkIUZ6A7PBcjs.setDbEngine.call(void 0, database);
914
- _chunkIUZ6A7PBcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
917
+ const app = _chunkDGYPIIJEcjs.createHttpApp.call(void 0, config);
918
+ if (database) _chunkGWMW6XY7cjs.setDbEngine.call(void 0, database);
919
+ _chunkGWMW6XY7cjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
915
920
  const poolWorkers = clusterEnabled ? _nullishCoalesce(workers, () => ( _os2.default.cpus().length)) : 1;
916
921
  const reportsPools = !clusterEnabled || _optionalChain([_cluster2.default, 'access', _12 => _12.worker, 'optionalAccess', _13 => _13.id]) === 1;
917
922
  if (database === "mongodb" && databaseUrl) {
918
- const conn = await _chunkR2K7AFIBcjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
919
- _chunkR2K7AFIBcjs.setDbClient.call(void 0, conn);
923
+ const conn = await _chunkSOU3PBJCcjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
924
+ _chunkSOU3PBJCcjs.setDbClient.call(void 0, conn);
920
925
  if (reportsPools) {
921
926
  const max = _nullishCoalesce(_optionalChain([config, 'access', _14 => _14.databasePool, 'optionalAccess', _15 => _15.max]), () => ( 100));
922
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info(
927
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(
923
928
  `MongoDB connections: up to ${poolWorkers * max} from this machine (${poolWorkers} worker(s) \xD7 maxPoolSize ${max})`
924
929
  );
925
930
  }
926
931
  } else if (database === "postgresql" && databaseUrl) {
927
- const pool = await _chunkJP36TLL4cjs.connectPostgres.call(void 0, databaseUrl, config.databasePool);
928
- _chunkR2K7AFIBcjs.setDbClient.call(void 0, pool);
932
+ const pool = await _chunkQSIP7YLWcjs.connectPostgres.call(void 0, databaseUrl, config.databasePool);
933
+ _chunkSOU3PBJCcjs.setDbClient.call(void 0, pool);
929
934
  if (reportsPools) {
930
935
  const max = _nullishCoalesce(_optionalChain([config, 'access', _16 => _16.databasePool, 'optionalAccess', _17 => _17.max]), () => ( 10));
931
936
  const boss = config.tasks && config.tasks.backend === "pg-boss" && !config.tasks.connectionString ? 10 : 0;
932
937
  const breakdown = `${poolWorkers} worker(s) \xD7 (pool ${max}${boss ? ` + pg-boss ${boss}` : ""})`;
933
- await _chunkJP36TLL4cjs.checkConnectionBudget.call(void 0, poolWorkers * (max + boss), breakdown);
938
+ await _chunkQSIP7YLWcjs.checkConnectionBudget.call(void 0, poolWorkers * (max + boss), breakdown);
934
939
  }
935
940
  }
936
941
  if (config.cache) {
937
- await _chunkY4NKIXULcjs.configureCache.call(void 0, config.cache);
942
+ await _chunkIEF6AEK3cjs.configureCache.call(void 0, config.cache);
938
943
  }
939
944
  if (jwtSecret) {
940
- _chunkY4NKIXULcjs.configureAuth.call(void 0, {
945
+ _chunkIEF6AEK3cjs.configureAuth.call(void 0, {
941
946
  secret: jwtSecret,
942
947
  strategy: authStrategy,
943
948
  expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
@@ -949,7 +954,7 @@ async function ignite(config) {
949
954
  }
950
955
  if (config.tasks) {
951
956
  if (config.tasks.backend === "bullmq") {
952
- await _chunkTBIVIR6Lcjs.initBullMQ.call(void 0, {
957
+ await _chunkDTMDJGRWcjs.initBullMQ.call(void 0, {
953
958
  redisUrl: _nullishCoalesce(config.tasks.redisUrl, () => ( "redis://localhost:6379")),
954
959
  concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
955
960
  enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
@@ -962,7 +967,7 @@ async function ignite(config) {
962
967
  '[EFC] tasks.backend "pg-boss" needs tasks.connectionString or databaseUrl'
963
968
  );
964
969
  }
965
- await _chunk7BC3AN7Rcjs.initPgBoss.call(void 0, {
970
+ await _chunk6WTMRZS7cjs.initPgBoss.call(void 0, {
966
971
  connectionString,
967
972
  concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
968
973
  enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
@@ -971,9 +976,18 @@ async function ignite(config) {
971
976
  });
972
977
  }
973
978
  }
974
- const routes = _chunk4GHK27JAcjs.scanDir.call(void 0, apiDir);
979
+ const routes = _chunkWHBSVYUYcjs.scanDir.call(void 0, apiDir);
975
980
  const apiRouter = _express2.default.Router();
976
- const mounted = await _chunk74BSJXWDcjs.mountRoutes.call(void 0, apiRouter, routes);
981
+ const mounted = await _chunkDGYPIIJEcjs.mountRoutes.call(void 0, apiRouter, routes);
982
+ if (config.openapi) {
983
+ const meta = readProjectMeta();
984
+ const options = config.openapi === true ? {} : config.openapi;
985
+ await _chunkDGYPIIJEcjs.mountOpenAPI.call(void 0, app, mounted, {
986
+ info: { title: meta.name, version: meta.version },
987
+ ...options,
988
+ basePath
989
+ });
990
+ }
977
991
  app.use(basePath, apiRouter);
978
992
  if (config.dashboard !== false && process.env["NODE_ENV"] === "development") {
979
993
  app.get("/", (_req, res) => {
@@ -982,16 +996,19 @@ async function ignite(config) {
982
996
  res.send(generateDashboard(mounted, basePath, port, name, version));
983
997
  });
984
998
  }
985
- _chunk74BSJXWDcjs.mountErrorHandler.call(void 0, app, onError);
999
+ _chunkDGYPIIJEcjs.mountErrorHandler.call(void 0, app, onError);
986
1000
  return new Promise((resolve, reject) => {
987
- const server = app.listen(port);
1001
+ const server = _http2.default.createServer(app);
1002
+ if (config.websocket !== false && mounted.some((route) => route.websocket))
1003
+ _chunkDGYPIIJEcjs.attachWebSockets.call(void 0, server, app, config.websocket);
988
1004
  server.once("listening", () => {
989
1005
  const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _18 => _18.worker, 'optionalAccess', _19 => _19.id]), () => ( "primary"));
990
1006
  const addr = server.address();
991
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info(`Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _20 => _20.port]), () => ( port))}`);
1007
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _20 => _20.port]), () => ( port))}`);
992
1008
  resolve(server);
993
1009
  });
994
1010
  server.once("error", reject);
1011
+ server.listen(port);
995
1012
  });
996
1013
  }
997
1014
  function gracefulShutdown(server, timeoutMs = 1e4) {
@@ -999,21 +1016,22 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
999
1016
  const shutdown = (signal) => {
1000
1017
  if (shuttingDown) return;
1001
1018
  shuttingDown = true;
1002
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info(`${signal} received \u2014 closing server gracefully\u2026`);
1019
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`${signal} received \u2014 closing server gracefully\u2026`);
1003
1020
  if (server) {
1021
+ const websocketDrain = _chunkDGYPIIJEcjs.closeWebSockets.call(void 0, server, Math.max(1, Math.min(1e3, timeoutMs / 2)));
1004
1022
  server.closeIdleConnections();
1005
1023
  server.close(() => {
1006
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).info("Server closed");
1007
- Promise.all([_chunkTBIVIR6Lcjs.closeBullMQ.call(void 0, ), _chunk7BC3AN7Rcjs.closePgBoss.call(void 0, ), _chunkY4NKIXULcjs.closeCache.call(void 0, )]).catch((err) => _chunkJP36TLL4cjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1024
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info("Server closed");
1025
+ Promise.all([websocketDrain, _chunkDTMDJGRWcjs.closeBullMQ.call(void 0, ), _chunk6WTMRZS7cjs.closePgBoss.call(void 0, ), _chunkIEF6AEK3cjs.closeCache.call(void 0, )]).catch((err) => _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1008
1026
  });
1009
1027
  setTimeout(() => {
1010
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).error("Forced exit after timeout");
1028
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
1011
1029
  process.exit(1);
1012
1030
  }, timeoutMs).unref();
1013
1031
  } else {
1014
1032
  shutdownMaster();
1015
1033
  setTimeout(() => {
1016
- _chunkJP36TLL4cjs.getLogger.call(void 0, ).error("Workers did not exit in time \u2014 forcing primary exit");
1034
+ _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error("Workers did not exit in time \u2014 forcing primary exit");
1017
1035
  process.exit(1);
1018
1036
  }, timeoutMs + 2e3).unref();
1019
1037
  }
@@ -1045,5 +1063,9 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1045
1063
 
1046
1064
 
1047
1065
 
1048
- exports.HttpError = _chunkAGOYTFROcjs.HttpError; exports.ModelValidationError = _chunkIUZ6A7PBcjs.ModelValidationError; exports.cache = _chunkY4NKIXULcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkR2K7AFIBcjs.db; exports.defineCollection = _chunkR2K7AFIBcjs.defineCollection; exports.defineModel = _chunkR2K7AFIBcjs.defineModel; exports.defineTable = _chunkR2K7AFIBcjs.defineTable; exports.getDbClient = _chunkR2K7AFIBcjs.getDbClient; exports.getLogger = _chunkJP36TLL4cjs.getLogger; exports.getQueryMetrics = _chunkJP36TLL4cjs.getQueryMetrics; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkAGOYTFROcjs.isHttpError; exports.listTasks = _chunkH2PVWCWCcjs.listTasks; exports.logger = _chunkJP36TLL4cjs.logger; exports.rateLimit = rateLimit; exports.resetQueryMetrics = _chunkJP36TLL4cjs.resetQueryMetrics; exports.scanDir = _chunk4GHK27JAcjs.scanDir; exports.setDbClient = _chunkR2K7AFIBcjs.setDbClient; exports.transaction = _chunkR2K7AFIBcjs.transaction; exports.workerCount = workerCount;
1049
- //# sourceMappingURL=index.cjs.map
1066
+
1067
+
1068
+
1069
+ exports.HttpError = _chunkAGOYTFROcjs.HttpError; exports.ModelValidationError = _chunkGWMW6XY7cjs.ModelValidationError; exports.attachWebSockets = _chunkDGYPIIJEcjs.attachWebSockets; exports.cache = _chunkIEF6AEK3cjs.cache; exports.cacheResponse = cacheResponse; exports.closeWebSockets = _chunkDGYPIIJEcjs.closeWebSockets; exports.compose = compose; exports.db = _chunkSOU3PBJCcjs.db; exports.defineCollection = _chunkSOU3PBJCcjs.defineCollection; exports.defineModel = _chunkSOU3PBJCcjs.defineModel; exports.defineTable = _chunkSOU3PBJCcjs.defineTable; exports.generateOpenAPI = _chunkDGYPIIJEcjs.generateOpenAPI; exports.getDbClient = _chunkSOU3PBJCcjs.getDbClient; exports.getLogger = _chunkQSIP7YLWcjs.getLogger; exports.getQueryMetrics = _chunkQSIP7YLWcjs.getQueryMetrics; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkAGOYTFROcjs.isHttpError; exports.listTasks = _chunkH2PVWCWCcjs.listTasks; exports.logger = _chunkQSIP7YLWcjs.logger; exports.rateLimit = rateLimit; exports.resetQueryMetrics = _chunkQSIP7YLWcjs.resetQueryMetrics; exports.scanDir = _chunkWHBSVYUYcjs.scanDir; exports.setDbClient = _chunkSOU3PBJCcjs.setDbClient; exports.transaction = _chunkSOU3PBJCcjs.transaction; exports.workerCount = workerCount;
1070
+ //# sourceMappingURL=index.cjs.map
1071
+ exports.generateOpenAPI = require("./openapi-cjs.cjs").generateOpenAPI;