express-file-cluster 0.3.15 → 0.7.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 +71 -33
  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-277BSYVH.js +127 -0
  8. package/dist/chunk-277BSYVH.js.map +1 -0
  9. package/dist/chunk-6OGOVV57.js +3847 -0
  10. package/dist/chunk-6OGOVV57.js.map +1 -0
  11. package/dist/chunk-7YEX4MQV.cjs +38 -0
  12. package/dist/chunk-7YEX4MQV.cjs.map +1 -0
  13. package/dist/chunk-AZYXQU3Z.cjs +3847 -0
  14. package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
  15. package/dist/chunk-BUBXO7WU.js +170 -0
  16. package/dist/chunk-BUBXO7WU.js.map +1 -0
  17. package/dist/chunk-LJNSJFOL.js +38 -0
  18. package/dist/chunk-LJNSJFOL.js.map +1 -0
  19. package/dist/chunk-MGH4VDV3.cjs +170 -0
  20. package/dist/chunk-MGH4VDV3.cjs.map +1 -0
  21. package/dist/chunk-R34R7QPD.cjs +116 -0
  22. package/dist/chunk-R34R7QPD.cjs.map +1 -0
  23. package/dist/chunk-RS4MXCPW.js +116 -0
  24. package/dist/chunk-RS4MXCPW.js.map +1 -0
  25. package/dist/chunk-T4OHFU5T.cjs +154 -0
  26. package/dist/chunk-T4OHFU5T.cjs.map +1 -0
  27. package/dist/chunk-TI24L4XE.cjs.map +1 -1
  28. package/dist/chunk-TRC4DUZB.js +438 -0
  29. package/dist/chunk-TRC4DUZB.js.map +1 -0
  30. package/dist/chunk-TYR2GZZE.cjs +196 -0
  31. package/dist/chunk-TYR2GZZE.cjs.map +1 -0
  32. package/dist/chunk-UBQYQPBU.js +154 -0
  33. package/dist/chunk-UBQYQPBU.js.map +1 -0
  34. package/dist/chunk-UTM4PEVG.js +196 -0
  35. package/dist/chunk-UTM4PEVG.js.map +1 -0
  36. package/dist/chunk-YL37D6KM.cjs +127 -0
  37. package/dist/chunk-YL37D6KM.cjs.map +1 -0
  38. package/dist/chunk-ZDM5JHVK.cjs +438 -0
  39. package/dist/chunk-ZDM5JHVK.cjs.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 +326 -0
  55. package/dist/docs/api-reference/table.md +458 -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 +108 -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 +309 -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 +264 -391
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +699 -7
  94. package/dist/index.d.ts +699 -7
  95. package/dist/index.js +258 -385
  96. package/dist/index.js.map +1 -1
  97. package/dist/pgboss-backend-QKBXVJ6B.js +14 -0
  98. package/dist/pgboss-backend-QKBXVJ6B.js.map +1 -0
  99. package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
  100. package/dist/pgboss-backend-TCHI7CHM.cjs.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-B6lVw4bj.d.cts +588 -0
  105. package/dist/types-B6lVw4bj.d.ts +588 -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
package/dist/index.js CHANGED
@@ -1,17 +1,52 @@
1
1
  import {
2
+ cache,
3
+ closeCache,
2
4
  configureAuth,
3
- getCurrentUser,
4
- runWithContext
5
- } from "./chunk-VIP3PFWZ.js";
5
+ configureCache,
6
+ servePrimaryCache
7
+ } from "./chunk-TRC4DUZB.js";
8
+ import {
9
+ scanDir
10
+ } from "./chunk-RS4MXCPW.js";
11
+ import {
12
+ closeBullMQ,
13
+ initBullMQ
14
+ } from "./chunk-UBQYQPBU.js";
15
+ import {
16
+ HttpError,
17
+ ModelValidationError,
18
+ connectMongo,
19
+ db,
20
+ defineModel,
21
+ defineTable,
22
+ getDbClient,
23
+ isHttpError,
24
+ setAutoSync,
25
+ setDbClient,
26
+ setDbEngine,
27
+ transaction
28
+ } from "./chunk-6OGOVV57.js";
29
+ import {
30
+ configureQueryLog,
31
+ connectPostgres
32
+ } from "./chunk-BUBXO7WU.js";
33
+ import {
34
+ closePgBoss,
35
+ initPgBoss
36
+ } from "./chunk-UTM4PEVG.js";
37
+ import "./chunk-LJNSJFOL.js";
6
38
  import {
7
39
  listTasks,
8
- registerTask,
9
- setEnqueueImpl,
10
- taskRegistry
40
+ registerTask
11
41
  } from "./chunk-HBYSKULC.js";
12
42
  import {
13
- scanDir
14
- } from "./chunk-KOHLLUN7.js";
43
+ configureLogger,
44
+ getCurrentUser,
45
+ getLogger,
46
+ logger,
47
+ requestLogger,
48
+ runWithContext
49
+ } from "./chunk-277BSYVH.js";
15
50
 
16
51
  // src/index.ts
17
52
  import fs2 from "fs";
@@ -22,6 +57,70 @@ import cluster2 from "cluster";
22
57
  import os from "os";
23
58
  import path2 from "path";
24
59
 
60
+ // src/router/validate.ts
61
+ var LOCATIONS = ["params", "query", "body"];
62
+ function isRequestSchema(value) {
63
+ return value != null && typeof value === "object" && LOCATIONS.some((loc) => loc in value);
64
+ }
65
+ function schemaFor(schema, method) {
66
+ if (!schema) return void 0;
67
+ const byMethod = schema[method];
68
+ if (isRequestSchema(byMethod)) return byMethod;
69
+ return isRequestSchema(schema) ? schema : void 0;
70
+ }
71
+ function pathToString(path3) {
72
+ if (!path3) return "";
73
+ return path3.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).map(String).join(".");
74
+ }
75
+ async function run(validator, input) {
76
+ const std = validator["~standard"];
77
+ if (std && typeof std.validate === "function") {
78
+ return await std.validate(input);
79
+ }
80
+ const v = validator;
81
+ const parse = v.safeParseAsync ?? v.safeParse;
82
+ if (typeof parse !== "function") {
83
+ throw new Error("[EFC] Route schema entries must be Standard Schema validators (e.g. zod)");
84
+ }
85
+ const r = await parse.call(validator, input);
86
+ return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: "Invalid" }] };
87
+ }
88
+ function validateRequest(schema) {
89
+ return (req, res, next) => {
90
+ void (async () => {
91
+ const issues = [];
92
+ const parsed = {};
93
+ for (const location of LOCATIONS) {
94
+ const validator = schema[location];
95
+ if (!validator) continue;
96
+ const result = await run(validator, req[location]);
97
+ if (result.issues) {
98
+ for (const issue of result.issues) {
99
+ issues.push({ location, path: pathToString(issue.path), message: issue.message });
100
+ }
101
+ } else {
102
+ parsed[location] = result.value;
103
+ }
104
+ }
105
+ if (issues.length > 0) {
106
+ res.status(400).json({ error: "Validation failed", statusCode: 400, issues });
107
+ return;
108
+ }
109
+ for (const location of LOCATIONS) {
110
+ if (location in parsed) {
111
+ Object.defineProperty(req, location, {
112
+ value: parsed[location],
113
+ writable: true,
114
+ configurable: true,
115
+ enumerable: true
116
+ });
117
+ }
118
+ }
119
+ next();
120
+ })().catch(next);
121
+ };
122
+ }
123
+
25
124
  // src/router/mount.ts
26
125
  var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
27
126
  function asyncWrap(handler) {
@@ -29,6 +128,25 @@ function asyncWrap(handler) {
29
128
  Promise.resolve(handler(req, res, next)).catch(next);
30
129
  };
31
130
  }
131
+ function namedParams(route) {
132
+ const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
133
+ return (req, _res, next) => {
134
+ const positional = req.params;
135
+ const named = {};
136
+ route.params.forEach((name, i) => {
137
+ const value = positional[String(i)];
138
+ if (value === void 0 || value === "") {
139
+ named[name] = catchAlls.has(name) ? [] : void 0;
140
+ } else if (catchAlls.has(name)) {
141
+ named[name] = value.split("/").filter(Boolean).map(decodeURIComponent);
142
+ } else {
143
+ named[name] = decodeURIComponent(value);
144
+ }
145
+ });
146
+ req.params = named;
147
+ next();
148
+ };
149
+ }
32
150
  async function mountRoutes(app, routes) {
33
151
  const mounted = [];
34
152
  for (const route of routes) {
@@ -36,14 +154,21 @@ async function mountRoutes(app, routes) {
36
154
  const routeMiddlewares = Array.isArray(mod["middlewares"]) ? mod["middlewares"] : [];
37
155
  const raw = mod["meta"];
38
156
  const meta = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
157
+ const schema = mod["schema"] != null && typeof mod["schema"] === "object" ? mod["schema"] : void 0;
158
+ const routePath = route.pattern ?? route.urlPath;
159
+ const paramMapper = route.pattern ? [namedParams(route)] : [];
39
160
  const implemented = [];
40
161
  const unimplemented = [];
41
162
  for (const method of HTTP_METHODS) {
42
163
  if (typeof mod[method] === "function") {
43
164
  implemented.push(method);
165
+ const methodSchema = schemaFor(schema, method);
166
+ const validation = methodSchema ? [validateRequest(methodSchema)] : [];
44
167
  app[method.toLowerCase()](
45
- route.urlPath,
168
+ routePath,
169
+ ...paramMapper,
46
170
  ...routeMiddlewares,
171
+ ...validation,
47
172
  asyncWrap(mod[method])
48
173
  );
49
174
  } else {
@@ -52,7 +177,7 @@ async function mountRoutes(app, routes) {
52
177
  }
53
178
  if (implemented.length > 0 && unimplemented.length > 0) {
54
179
  const allowHeader = implemented.join(", ");
55
- app.all(route.urlPath, (req, res, next) => {
180
+ app.all(routePath, (req, res, next) => {
56
181
  if (unimplemented.includes(req.method)) {
57
182
  res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
58
183
  } else {
@@ -73,11 +198,15 @@ function workerCount() {
73
198
  }
74
199
  function shutdownMaster() {
75
200
  isShuttingDown = true;
76
- console.log(`[EFC] Cluster master (pid=${process.pid}) shutting down, waiting for workers\u2026`);
201
+ getLogger().info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
202
+ if (workerCount() === 0) process.exit(0);
203
+ for (const worker of Object.values(cluster.workers ?? {})) {
204
+ worker?.process.kill("SIGTERM");
205
+ }
77
206
  }
78
207
  function runMaster(options = {}) {
79
208
  const count = options.workers ?? 1;
80
- console.log(`[EFC] Primary ${process.pid} starting ${count} workers`);
209
+ getLogger().info(`Primary ${process.pid} starting ${count} workers`);
81
210
  for (let i = 0; i < count; i++) {
82
211
  cluster.fork();
83
212
  }
@@ -87,280 +216,19 @@ function runMaster(options = {}) {
87
216
  cluster.on("exit", (worker, code, signal) => {
88
217
  const exitCode = code ?? (signal ? -1 : 0);
89
218
  if (isShuttingDown) {
90
- console.log(`[EFC] Worker ${worker.id} gracefully exited`);
219
+ getLogger().info(`Worker ${worker.id} gracefully exited`);
91
220
  if (workerCount() === 0) {
92
- console.log("[EFC] All workers exited. Primary exiting.");
221
+ getLogger().info("All workers exited. Primary exiting.");
93
222
  process.exit(0);
94
223
  }
95
224
  return;
96
225
  }
97
- console.warn(`[EFC] Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
226
+ getLogger().warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
98
227
  options.onWorkerCrash?.(worker.id, exitCode);
99
228
  cluster.fork();
100
229
  });
101
230
  }
102
231
 
103
- // src/errors.ts
104
- var HttpError = class _HttpError extends Error {
105
- statusCode;
106
- constructor(statusCode, message) {
107
- super(message);
108
- this.name = "HttpError";
109
- this.statusCode = statusCode;
110
- Error.captureStackTrace(this, _HttpError);
111
- }
112
- /**
113
- * Wraps an unknown caught value into an `HttpError`.
114
- * If the value is already an `HttpError`, it is returned as-is.
115
- * Otherwise the `message` from the caught `Error` (or a fallback) is used.
116
- *
117
- * @example
118
- * } catch (err) {
119
- * throw HttpError.from(err, 500, 'Something went wrong');
120
- * }
121
- */
122
- static from(err, statusCode = 500, fallback = "Internal Server Error") {
123
- if (err instanceof _HttpError) return err;
124
- const message = err instanceof Error ? err.message : fallback;
125
- return new _HttpError(statusCode, message);
126
- }
127
- /** Returns a plain object representation suitable for JSON serialization. */
128
- toJSON() {
129
- return {
130
- statusCode: this.statusCode,
131
- error: this.name,
132
- message: this.message
133
- };
134
- }
135
- };
136
- function isHttpError(value) {
137
- return value instanceof HttpError;
138
- }
139
-
140
- // src/db/mongo.ts
141
- var mongoose;
142
- async function loadMongoose() {
143
- if (mongoose) return mongoose;
144
- try {
145
- mongoose = await import("mongoose");
146
- return mongoose;
147
- } catch {
148
- throw new Error("[EFC] mongoose is not installed. Run: npm install mongoose");
149
- }
150
- }
151
- async function connectMongo(url) {
152
- const mg = await loadMongoose();
153
- await mg.connect(url);
154
- console.log("[EFC] MongoDB connected");
155
- return mg.connection;
156
- }
157
-
158
- // src/db/model.ts
159
- import { randomUUID, randomBytes } from "crypto";
160
- function normalise(doc) {
161
- const id = doc["_id"] ? String(doc["_id"]) : "";
162
- return { ...doc, id };
163
- }
164
- var STATIC_DEFAULT_OPERATORS = {
165
- $now: () => /* @__PURE__ */ new Date(),
166
- $uuid: () => randomUUID(),
167
- $timestamp: () => Date.now(),
168
- $shortId: () => randomBytes(12).toString("base64url")
169
- };
170
- var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
171
- function isCurrentUserOperator(value) {
172
- return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
173
- }
174
- function isDefaultOperator(value) {
175
- return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
176
- }
177
- function resolveDefault(value, mg) {
178
- if (!isDefaultOperator(value)) return value;
179
- if (value === "$objectId") return () => new mg.Types.ObjectId();
180
- if (value === "$currentUser") return () => getCurrentUser();
181
- if (isCurrentUserOperator(value)) {
182
- const key = value.slice("$currentUser.".length);
183
- return () => getCurrentUser()?.[key];
184
- }
185
- return STATIC_DEFAULT_OPERATORS[value];
186
- }
187
- function isNestedArraySchema(def) {
188
- return Array.isArray(def);
189
- }
190
- function primitiveCtor(type, mg) {
191
- switch (type) {
192
- case "string":
193
- return String;
194
- case "number":
195
- return Number;
196
- case "boolean":
197
- return Boolean;
198
- case "date":
199
- return Date;
200
- case "object":
201
- return Object;
202
- case "objectId":
203
- return mg.Schema.Types.ObjectId;
204
- case "array":
205
- return Array;
206
- }
207
- }
208
- function buildFieldEntry(def, mg) {
209
- const entry = {};
210
- if (def.type === "array") {
211
- if (def.of === "objectId") {
212
- const item = { type: mg.Schema.Types.ObjectId };
213
- if (def.ref !== void 0) item["ref"] = def.ref;
214
- entry["type"] = [item];
215
- } else if (def.of) {
216
- entry["type"] = [primitiveCtor(def.of, mg)];
217
- } else {
218
- entry["type"] = Array;
219
- }
220
- } else {
221
- entry["type"] = primitiveCtor(def.type, mg);
222
- if (def.type === "objectId" && def.ref !== void 0) entry["ref"] = def.ref;
223
- }
224
- if (def.required !== void 0) entry["required"] = def.required;
225
- if (def.unique !== void 0) entry["unique"] = def.unique;
226
- if (def.default !== void 0) entry["default"] = resolveDefault(def.default, mg);
227
- if (def.enum !== void 0) entry["enum"] = def.enum;
228
- return entry;
229
- }
230
- function buildMongooseSchema(schema, mg) {
231
- const out = {};
232
- for (const [key, def] of Object.entries(schema)) {
233
- if (isNestedArraySchema(def)) {
234
- out[key] = def[0] ? [buildMongooseSchema(def[0], mg)] : [];
235
- } else {
236
- out[key] = buildFieldEntry(def, mg);
237
- }
238
- }
239
- return out;
240
- }
241
- function collectSequenceFields(name, schema) {
242
- const fields = [];
243
- for (const [path3, def] of Object.entries(schema)) {
244
- if (isNestedArraySchema(def)) continue;
245
- if (def.sequence) {
246
- const key = typeof def.sequence === "string" ? def.sequence : `${name}.${path3}`;
247
- fields.push({ path: path3, key });
248
- }
249
- }
250
- return fields;
251
- }
252
- var COUNTER_MODEL_NAME = "__EFCCounter__";
253
- function getCounterModel(mg) {
254
- if (mg.models[COUNTER_MODEL_NAME]) {
255
- return mg.models[COUNTER_MODEL_NAME];
256
- }
257
- const counterSchema = new mg.Schema(
258
- { _id: { type: String, required: true }, seq: { type: Number, default: 0 } },
259
- { collection: "efc_counters", versionKey: false }
260
- );
261
- return mg.model(COUNTER_MODEL_NAME, counterSchema);
262
- }
263
- async function nextSequence(mg, key) {
264
- const Counter = getCounterModel(mg);
265
- const doc = await Counter.findByIdAndUpdate(
266
- key,
267
- { $inc: { seq: 1 } },
268
- { returnDocument: "after", upsert: true }
269
- ).lean();
270
- return doc.seq;
271
- }
272
- async function getModel(name, schema, options = {}) {
273
- let mg;
274
- try {
275
- const mod = await import("mongoose");
276
- mg = mod.default || mod;
277
- } catch {
278
- throw new Error("[EFC] mongoose is not installed. Run: npm install mongoose");
279
- }
280
- if (mg.models[name]) return mg.models[name];
281
- const schemaObj = buildMongooseSchema(schema, mg);
282
- const mongooseSchema = new mg.Schema(schemaObj, { timestamps: options.timestamps ?? true });
283
- const sequenceFields = collectSequenceFields(name, schema);
284
- if (sequenceFields.length > 0) {
285
- mongooseSchema.pre("validate", async function() {
286
- if (!this.isNew) return;
287
- for (const { path: path3, key } of sequenceFields) {
288
- if (this.get(path3) == null) {
289
- this.set(path3, await nextSequence(mg, key));
290
- }
291
- }
292
- });
293
- }
294
- return mg.model(name, mongooseSchema);
295
- }
296
- function defineModel(name, schema, options) {
297
- return {
298
- async find(filter = {}, queryOptions) {
299
- const M = await getModel(name, schema, options);
300
- const query = M.find(filter);
301
- if (queryOptions?.populate) query.populate(queryOptions.populate);
302
- const docs = await query.lean();
303
- return docs.map(normalise);
304
- },
305
- async findById(id, queryOptions) {
306
- const M = await getModel(name, schema, options);
307
- const query = M.findById(id);
308
- if (queryOptions?.populate) query.populate(queryOptions.populate);
309
- const doc = await query.lean();
310
- if (!doc) return null;
311
- return normalise(doc);
312
- },
313
- async findOne(filter, queryOptions) {
314
- const M = await getModel(name, schema, options);
315
- const query = M.findOne(filter);
316
- if (queryOptions?.populate) query.populate(queryOptions.populate);
317
- const doc = await query.lean();
318
- if (!doc) return null;
319
- return normalise(doc);
320
- },
321
- async create(data) {
322
- const M = await getModel(name, schema, options);
323
- const doc = await M.create(data);
324
- return normalise(doc.toObject());
325
- },
326
- async update(id, data) {
327
- const M = await getModel(name, schema, options);
328
- const doc = await M.findByIdAndUpdate(id, data, { returnDocument: "after" }).lean();
329
- if (!doc) return null;
330
- return normalise(doc);
331
- },
332
- async delete(id) {
333
- const M = await getModel(name, schema, options);
334
- await M.findByIdAndDelete(id);
335
- },
336
- async count(filter = {}) {
337
- const M = await getModel(name, schema, options);
338
- return M.countDocuments(filter);
339
- }
340
- };
341
- }
342
-
343
- // src/db/index.ts
344
- var _client = null;
345
- function setDbClient(client) {
346
- _client = client;
347
- }
348
- function getDbClient() {
349
- if (!_client) {
350
- throw new Error("[EFC] db not ready \u2014 accessed before Pre-Flight completed");
351
- }
352
- return _client;
353
- }
354
- var db = new Proxy({}, {
355
- get(_target, prop) {
356
- return getDbClient()[prop];
357
- },
358
- set(_target, prop, value) {
359
- getDbClient()[prop] = value;
360
- return true;
361
- }
362
- });
363
-
364
232
  // src/tasks/scanner.ts
365
233
  import fs from "fs";
366
234
  import path from "path";
@@ -374,113 +242,17 @@ async function scanTasks(tasksDir) {
374
242
  const mod = await import(filePath);
375
243
  const def = mod["default"];
376
244
  if (!def || typeof def.handler !== "function") {
377
- console.warn(`[EFC] Task file ${file} has no valid default export \u2014 skipping`);
245
+ getLogger().warn(`Task file ${file} has no valid default export \u2014 skipping`);
378
246
  continue;
379
247
  }
380
248
  registerTask(taskName, { ...def, filePath });
381
- console.log(`[EFC] Registered task: ${taskName}`);
249
+ getLogger().debug(`Registered task: ${taskName}`);
382
250
  } catch (err) {
383
- console.warn(`[EFC] Failed to load task ${file}:`, err);
251
+ getLogger().warn({ err }, `Failed to load task ${file}`);
384
252
  }
385
253
  }
386
254
  }
387
255
 
388
- // src/tasks/thread-runner.ts
389
- import { Worker, workerData, parentPort, isMainThread } from "worker_threads";
390
- if (!isMainThread) {
391
- const { handlerPath, payload } = workerData;
392
- (async () => {
393
- try {
394
- const mod = await import(handlerPath);
395
- const def = mod["default"];
396
- if (!def || typeof def.handler !== "function") {
397
- throw new Error(`[EFC] Thread runner: no valid task export in ${handlerPath}`);
398
- }
399
- await def.handler(payload);
400
- parentPort?.postMessage({ ok: true });
401
- } catch (err) {
402
- parentPort?.postMessage({ ok: false, error: String(err) });
403
- }
404
- })();
405
- }
406
- function runInThread(handlerPath, payload) {
407
- return new Promise((resolve, reject) => {
408
- const worker = new Worker(new URL("./thread-runner.js", import.meta.url), {
409
- workerData: { handlerPath, payload }
410
- });
411
- worker.on("message", (msg) => {
412
- if (msg.ok) resolve();
413
- else reject(new Error(msg.error ?? "Thread task failed"));
414
- });
415
- worker.on("error", reject);
416
- worker.on("exit", (code) => {
417
- if (code !== 0) reject(new Error(`Thread worker exited with code ${code}`));
418
- });
419
- });
420
- }
421
-
422
- // src/tasks/bullmq-backend.ts
423
- async function initBullMQ(opts) {
424
- let bullmq;
425
- try {
426
- bullmq = await import("bullmq");
427
- } catch {
428
- throw new Error("[EFC] bullmq is not installed. Run: npm install bullmq");
429
- }
430
- const connection = parseRedisUrl(opts.redisUrl);
431
- const queue = new bullmq.Queue("efc", { connection });
432
- const worker = new bullmq.Worker(
433
- "efc",
434
- async (job) => {
435
- const def = taskRegistry.get(job.name);
436
- if (!def) {
437
- throw new Error(`[EFC] No task registered for name: ${job.name}`);
438
- }
439
- if (def.options.thread && def.filePath) {
440
- await runInThread(def.filePath, job.data);
441
- } else {
442
- await def.handler(job.data);
443
- }
444
- },
445
- { connection, concurrency: opts.concurrency }
446
- );
447
- worker.on("failed", (job, err) => {
448
- console.error(`[EFC] Task ${job?.name ?? "unknown"} failed:`, err.message);
449
- });
450
- worker.on("completed", (job) => {
451
- console.log(`[EFC] Task ${job.name} completed (id=${job.id})`);
452
- });
453
- setEnqueueImpl(async (name, payload) => {
454
- const def = taskRegistry.get(name);
455
- if (!def) {
456
- throw new Error(
457
- `[EFC] Cannot enqueue unknown task: "${name}". Is the task file in tasksDir?`
458
- );
459
- }
460
- await queue.add(name, payload, {
461
- attempts: def.options.retries ?? 3,
462
- backoff: {
463
- type: def.options.backoff ?? "exponential",
464
- delay: 1e3
465
- }
466
- });
467
- });
468
- console.log("[EFC] BullMQ backend initialised");
469
- }
470
- function parseRedisUrl(url) {
471
- try {
472
- const u = new URL(url);
473
- const result = {
474
- host: u.hostname || "localhost",
475
- port: parseInt(u.port || "6379", 10)
476
- };
477
- if (u.password) result.password = u.password;
478
- return result;
479
- } catch {
480
- return { host: "localhost", port: 6379 };
481
- }
482
- }
483
-
484
256
  // src/dashboard.ts
485
257
  var HTTP_STATUS = {
486
258
  200: "OK",
@@ -1079,6 +851,38 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
1079
851
  </html>`;
1080
852
  }
1081
853
 
854
+ // src/cache/response.ts
855
+ var RESPONSE_PREFIX = "res:";
856
+ function cacheResponse(options) {
857
+ const opts = typeof options === "number" ? { ttl: options } : options;
858
+ return (req, res, next) => {
859
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
860
+ let scope = "";
861
+ if (opts.perUser) {
862
+ const user = getCurrentUser();
863
+ const id = user?.["sub"] ?? user?.["id"];
864
+ if (id === void 0) return next();
865
+ scope = `u:${String(id)}:`;
866
+ }
867
+ const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
868
+ void (async () => {
869
+ const hit = await cache.get(key);
870
+ if (hit) {
871
+ res.setHeader("X-Cache", "HIT");
872
+ res.status(hit.status).json(hit.body);
873
+ return;
874
+ }
875
+ res.setHeader("X-Cache", "MISS");
876
+ const json = res.json.bind(res);
877
+ res.json = (body) => {
878
+ if (res.statusCode === 200) void cache.set(key, { status: 200, body }, { ttl: opts.ttl });
879
+ return json(body);
880
+ };
881
+ next();
882
+ })().catch(next);
883
+ };
884
+ }
885
+
1082
886
  // src/compose.ts
1083
887
  function compose(...handlers) {
1084
888
  return (req, res, next) => {
@@ -1145,7 +949,12 @@ async function ignite(config) {
1145
949
  const jwtSecret = config.jwtSecret;
1146
950
  const authStrategy = config.authStrategy ?? "http-only";
1147
951
  const clusterEnabled = config.cluster ?? process.env["NODE_ENV"] === "production";
952
+ configureLogger(config.logging);
953
+ configureQueryLog(config.logging);
1148
954
  if (clusterEnabled && cluster2.isPrimary) {
955
+ if (config.cache && config.cache.backend === "memory") {
956
+ servePrimaryCache(config.cache.maxEntries ?? 1e4);
957
+ }
1149
958
  runMaster({
1150
959
  workers: workers ?? os.cpus().length,
1151
960
  ...onWorkerReady !== void 0 && { onWorkerReady },
@@ -1154,9 +963,26 @@ async function ignite(config) {
1154
963
  return;
1155
964
  }
1156
965
  const app = express();
966
+ app.set(
967
+ "json replacer",
968
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
969
+ );
1157
970
  app.use((_req, _res, next) => {
1158
971
  runWithContext({}, next);
1159
972
  });
973
+ app.use(requestLogger());
974
+ if (config.requestTimeout) {
975
+ const ms = config.requestTimeout;
976
+ app.use((_req, res, next) => {
977
+ const timer = setTimeout(() => {
978
+ if (!res.headersSent) res.status(408).json({ error: "Request Timeout", statusCode: 408 });
979
+ }, ms);
980
+ const clear = () => clearTimeout(timer);
981
+ res.once("finish", clear);
982
+ res.once("close", clear);
983
+ next();
984
+ });
985
+ }
1160
986
  const corsOption = config.cors ?? true;
1161
987
  if (corsOption !== false) {
1162
988
  const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
@@ -1169,9 +995,17 @@ async function ignite(config) {
1169
995
  for (const mw of globalMiddlewares) {
1170
996
  app.use(mw);
1171
997
  }
998
+ if (database) setDbEngine(database);
999
+ setAutoSync(config.autoSync ?? true);
1172
1000
  if (database === "mongodb" && databaseUrl) {
1173
1001
  const conn = await connectMongo(databaseUrl);
1174
1002
  setDbClient(conn);
1003
+ } else if (database === "postgresql" && databaseUrl) {
1004
+ const pool = await connectPostgres(databaseUrl);
1005
+ setDbClient(pool);
1006
+ }
1007
+ if (config.cache) {
1008
+ await configureCache(config.cache);
1175
1009
  }
1176
1010
  if (jwtSecret) {
1177
1011
  configureAuth({
@@ -1188,7 +1022,23 @@ async function ignite(config) {
1188
1022
  if (config.tasks.backend === "bullmq") {
1189
1023
  await initBullMQ({
1190
1024
  redisUrl: config.tasks.redisUrl ?? "redis://localhost:6379",
1191
- concurrency: config.tasks.concurrency ?? 5
1025
+ concurrency: config.tasks.concurrency ?? 5,
1026
+ enqueueTimeout: config.tasks.enqueueTimeout ?? 5e3,
1027
+ queue: config.tasks.queue ?? "efc"
1028
+ });
1029
+ } else if (config.tasks.backend === "pg-boss") {
1030
+ const connectionString = config.tasks.connectionString ?? databaseUrl;
1031
+ if (!connectionString) {
1032
+ throw new Error(
1033
+ '[EFC] tasks.backend "pg-boss" needs tasks.connectionString or databaseUrl'
1034
+ );
1035
+ }
1036
+ await initPgBoss({
1037
+ connectionString,
1038
+ concurrency: config.tasks.concurrency ?? 5,
1039
+ enqueueTimeout: config.tasks.enqueueTimeout ?? 5e3,
1040
+ queue: config.tasks.queue ?? "efc",
1041
+ ...config.tasks.schema !== void 0 && { schema: config.tasks.schema }
1192
1042
  });
1193
1043
  }
1194
1044
  }
@@ -1208,13 +1058,22 @@ async function ignite(config) {
1208
1058
  } else {
1209
1059
  app.use(
1210
1060
  (err, _req, res, _next) => {
1061
+ if (res.headersSent) {
1062
+ getLogger().warn({ err }, "Error after the response was sent");
1063
+ return;
1064
+ }
1211
1065
  const duckTyped = err instanceof Error && typeof err.statusCode === "number" ? err : null;
1212
1066
  if (isHttpError(err)) {
1213
- res.status(err.statusCode).json({ error: err.message, statusCode: err.statusCode });
1067
+ const issues = err.issues;
1068
+ res.status(err.statusCode).json({
1069
+ error: err.message,
1070
+ statusCode: err.statusCode,
1071
+ ...issues !== void 0 && { issues }
1072
+ });
1214
1073
  } else if (duckTyped) {
1215
1074
  res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
1216
1075
  } else {
1217
- console.error("[EFC] Unhandled error:", err);
1076
+ getLogger().error({ err }, "Unhandled error");
1218
1077
  res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
1219
1078
  }
1220
1079
  }
@@ -1225,44 +1084,58 @@ async function ignite(config) {
1225
1084
  server.once("listening", () => {
1226
1085
  const wid = cluster2.worker?.id ?? "primary";
1227
1086
  const addr = server.address();
1228
- console.log(`[EFC] Worker ${wid} listening on :${addr?.port ?? port}`);
1087
+ getLogger().info(`Worker ${wid} listening on :${addr?.port ?? port}`);
1229
1088
  resolve(server);
1230
1089
  });
1231
1090
  server.once("error", reject);
1232
1091
  });
1233
1092
  }
1234
1093
  function gracefulShutdown(server, timeoutMs = 1e4) {
1094
+ let shuttingDown = false;
1235
1095
  const shutdown = (signal) => {
1236
- console.log(`[EFC] ${signal} received \u2014 closing server gracefully\u2026`);
1096
+ if (shuttingDown) return;
1097
+ shuttingDown = true;
1098
+ getLogger().info(`${signal} received \u2014 closing server gracefully\u2026`);
1237
1099
  if (server) {
1238
1100
  server.closeIdleConnections();
1239
1101
  server.close(() => {
1240
- console.log("[EFC] Server closed");
1241
- process.exit(0);
1102
+ getLogger().info("Server closed");
1103
+ Promise.all([closeBullMQ(), closePgBoss(), closeCache()]).catch((err) => getLogger().error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1242
1104
  });
1243
1105
  setTimeout(() => {
1244
- console.error("[EFC] Forced exit after timeout");
1106
+ getLogger().error("Forced exit after timeout");
1245
1107
  process.exit(1);
1246
1108
  }, timeoutMs).unref();
1247
1109
  } else {
1248
1110
  shutdownMaster();
1111
+ setTimeout(() => {
1112
+ getLogger().error("Workers did not exit in time \u2014 forcing primary exit");
1113
+ process.exit(1);
1114
+ }, timeoutMs + 2e3).unref();
1249
1115
  }
1250
1116
  };
1251
- process.once("SIGTERM", () => shutdown("SIGTERM"));
1252
- process.once("SIGINT", () => shutdown("SIGINT"));
1117
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
1118
+ process.on("SIGINT", () => shutdown("SIGINT"));
1253
1119
  }
1254
1120
  export {
1255
1121
  HttpError,
1122
+ ModelValidationError,
1123
+ cache,
1124
+ cacheResponse,
1256
1125
  compose,
1257
1126
  db,
1258
1127
  defineModel,
1128
+ defineTable,
1259
1129
  getDbClient,
1130
+ getLogger,
1260
1131
  gracefulShutdown,
1261
1132
  ignite,
1262
1133
  isHttpError,
1263
1134
  listTasks,
1135
+ logger,
1264
1136
  scanDir,
1265
1137
  setDbClient,
1138
+ transaction,
1266
1139
  workerCount
1267
1140
  };
1268
1141
  //# sourceMappingURL=index.js.map