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.cjs CHANGED
@@ -2,16 +2,51 @@
2
2
 
3
3
 
4
4
 
5
- var _chunk6522HS2Jcjs = require('./chunk-6522HS2J.cjs');
6
5
 
7
6
 
7
+ var _chunkZDM5JHVKcjs = require('./chunk-ZDM5JHVK.cjs');
8
+
9
+
10
+ var _chunkR34R7QPDcjs = require('./chunk-R34R7QPD.cjs');
11
+
12
+
13
+
14
+ var _chunkT4OHFU5Tcjs = require('./chunk-T4OHFU5T.cjs');
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ var _chunkAZYXQU3Zcjs = require('./chunk-AZYXQU3Z.cjs');
29
+
30
+
31
+
32
+ var _chunkMGH4VDV3cjs = require('./chunk-MGH4VDV3.cjs');
33
+
34
+
35
+
36
+ var _chunkTYR2GZZEcjs = require('./chunk-TYR2GZZE.cjs');
37
+ require('./chunk-7YEX4MQV.cjs');
8
38
 
9
39
 
10
40
 
11
41
  var _chunkTI24L4XEcjs = require('./chunk-TI24L4XE.cjs');
12
42
 
13
43
 
14
- var _chunkDGVOJNR6cjs = require('./chunk-DGVOJNR6.cjs');
44
+
45
+
46
+
47
+
48
+
49
+ var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
15
50
 
16
51
  // src/index.ts
17
52
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
@@ -22,6 +57,70 @@ var _cluster = require('cluster'); var _cluster2 = _interopRequireDefault(_clust
22
57
  var _os = require('os'); var _os2 = _interopRequireDefault(_os);
23
58
  var _path = require('path'); var _path2 = _interopRequireDefault(_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 = _nullishCoalesce(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: _nullishCoalesce(_optionalChain([r, 'access', _ => _.error, 'optionalAccess', _2 => _2.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 = _nullishCoalesce(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,294 +198,37 @@ 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
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).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(_nullishCoalesce(_cluster2.default.workers, () => ( {})))) {
204
+ _optionalChain([worker, 'optionalAccess', _3 => _3.process, 'access', _4 => _4.kill, 'call', _5 => _5("SIGTERM")]);
205
+ }
77
206
  }
78
207
  function runMaster(options = {}) {
79
208
  const count = _nullishCoalesce(options.workers, () => ( 1));
80
- console.log(`[EFC] Primary ${process.pid} starting ${count} workers`);
209
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).info(`Primary ${process.pid} starting ${count} workers`);
81
210
  for (let i = 0; i < count; i++) {
82
211
  _cluster2.default.fork();
83
212
  }
84
213
  _cluster2.default.on("online", (worker) => {
85
- _optionalChain([options, 'access', _ => _.onWorkerReady, 'optionalCall', _2 => _2(worker.id)]);
214
+ _optionalChain([options, 'access', _6 => _6.onWorkerReady, 'optionalCall', _7 => _7(worker.id)]);
86
215
  });
87
216
  _cluster2.default.on("exit", (worker, code, signal) => {
88
217
  const exitCode = _nullishCoalesce(code, () => ( (signal ? -1 : 0)));
89
218
  if (isShuttingDown) {
90
- console.log(`[EFC] Worker ${worker.id} gracefully exited`);
219
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).info(`Worker ${worker.id} gracefully exited`);
91
220
  if (workerCount() === 0) {
92
- console.log("[EFC] All workers exited. Primary exiting.");
221
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).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`);
98
- _optionalChain([options, 'access', _3 => _3.onWorkerCrash, 'optionalCall', _4 => _4(worker.id, exitCode)]);
226
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
227
+ _optionalChain([options, 'access', _8 => _8.onWorkerCrash, 'optionalCall', _9 => _9(worker.id, exitCode)]);
99
228
  _cluster2.default.fork();
100
229
  });
101
230
  }
102
231
 
103
- // src/errors.ts
104
- var HttpError = class _HttpError extends Error {
105
-
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 Promise.resolve().then(() => _interopRequireWildcard(require("mongoose")));
146
- return mongoose;
147
- } catch (e) {
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
- var _crypto = require('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: () => _crypto.randomUUID.call(void 0, ),
167
- $timestamp: () => Date.now(),
168
- $shortId: () => _crypto.randomBytes.call(void 0, 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 () => _chunk6522HS2Jcjs.getCurrentUser.call(void 0, );
181
- if (isCurrentUserOperator(value)) {
182
- const key = value.slice("$currentUser.".length);
183
- return () => _optionalChain([_chunk6522HS2Jcjs.getCurrentUser.call(void 0, ), 'optionalAccess', _5 => _5[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 Promise.resolve().then(() => _interopRequireWildcard(require("mongoose")));
276
- mg = mod.default || mod;
277
- } catch (e2) {
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: _nullishCoalesce(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 (_optionalChain([queryOptions, 'optionalAccess', _6 => _6.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 (_optionalChain([queryOptions, 'optionalAccess', _7 => _7.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 (_optionalChain([queryOptions, 'optionalAccess', _8 => _8.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
 
366
234
 
@@ -374,113 +242,17 @@ async function scanTasks(tasksDir) {
374
242
  const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(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
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(`Task file ${file} has no valid default export \u2014 skipping`);
378
246
  continue;
379
247
  }
380
248
  _chunkTI24L4XEcjs.registerTask.call(void 0, taskName, { ...def, filePath });
381
- console.log(`[EFC] Registered task: ${taskName}`);
249
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).debug(`Registered task: ${taskName}`);
382
250
  } catch (err) {
383
- console.warn(`[EFC] Failed to load task ${file}:`, err);
251
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn({ err }, `Failed to load task ${file}`);
384
252
  }
385
253
  }
386
254
  }
387
255
 
388
- // src/tasks/thread-runner.ts
389
- var _worker_threads = require('worker_threads');
390
- if (!_worker_threads.isMainThread) {
391
- const { handlerPath, payload } = _worker_threads.workerData;
392
- (async () => {
393
- try {
394
- const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(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
- _optionalChain([_worker_threads.parentPort, 'optionalAccess', _9 => _9.postMessage, 'call', _10 => _10({ ok: true })]);
401
- } catch (err) {
402
- _optionalChain([_worker_threads.parentPort, 'optionalAccess', _11 => _11.postMessage, 'call', _12 => _12({ ok: false, error: String(err) })]);
403
- }
404
- })();
405
- }
406
- function runInThread(handlerPath, payload) {
407
- return new Promise((resolve, reject) => {
408
- const worker = new (0, _worker_threads.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(_nullishCoalesce(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 Promise.resolve().then(() => _interopRequireWildcard(require("bullmq")));
427
- } catch (e3) {
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 = _chunkTI24L4XEcjs.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 ${_nullishCoalesce(_optionalChain([job, 'optionalAccess', _13 => _13.name]), () => ( "unknown"))} failed:`, err.message);
449
- });
450
- worker.on("completed", (job) => {
451
- console.log(`[EFC] Task ${job.name} completed (id=${job.id})`);
452
- });
453
- _chunkTI24L4XEcjs.setEnqueueImpl.call(void 0, async (name, payload) => {
454
- const def = _chunkTI24L4XEcjs.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: _nullishCoalesce(def.options.retries, () => ( 3)),
462
- backoff: {
463
- type: _nullishCoalesce(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 (e4) {
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 = _chunkYL37D6KMcjs.getCurrentUser.call(void 0, );
863
+ const id = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _10 => _10["sub"]]), () => ( _optionalChain([user, 'optionalAccess', _11 => _11["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 _chunkZDM5JHVKcjs.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 _chunkZDM5JHVKcjs.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) => {
@@ -1135,7 +939,7 @@ async function ignite(config) {
1135
939
  const raw = _fs2.default.readFileSync(_path2.default.join(process.cwd(), "package.json"), "utf8");
1136
940
  const pkg = JSON.parse(raw);
1137
941
  return { name: _nullishCoalesce(pkg.name, () => ( "API")), version: _nullishCoalesce(pkg.version, () => ( "")) };
1138
- } catch (e5) {
942
+ } catch (e) {
1139
943
  return { name: "API", version: "" };
1140
944
  }
1141
945
  }
@@ -1145,7 +949,12 @@ async function ignite(config) {
1145
949
  const jwtSecret = config.jwtSecret;
1146
950
  const authStrategy = _nullishCoalesce(config.authStrategy, () => ( "http-only"));
1147
951
  const clusterEnabled = _nullishCoalesce(config.cluster, () => ( process.env["NODE_ENV"] === "production"));
952
+ _chunkYL37D6KMcjs.configureLogger.call(void 0, config.logging);
953
+ _chunkMGH4VDV3cjs.configureQueryLog.call(void 0, config.logging);
1148
954
  if (clusterEnabled && _cluster2.default.isPrimary) {
955
+ if (config.cache && config.cache.backend === "memory") {
956
+ _chunkZDM5JHVKcjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
957
+ }
1149
958
  runMaster({
1150
959
  workers: _nullishCoalesce(workers, () => ( _os2.default.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 = _express2.default.call(void 0, );
966
+ app.set(
967
+ "json replacer",
968
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
969
+ );
1157
970
  app.use((_req, _res, next) => {
1158
- _chunk6522HS2Jcjs.runWithContext.call(void 0, {}, next);
971
+ _chunkYL37D6KMcjs.runWithContext.call(void 0, {}, next);
1159
972
  });
973
+ app.use(_chunkYL37D6KMcjs.requestLogger.call(void 0, ));
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 = _nullishCoalesce(config.cors, () => ( true));
1161
987
  if (corsOption !== false) {
1162
988
  const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
@@ -1169,12 +995,20 @@ async function ignite(config) {
1169
995
  for (const mw of globalMiddlewares) {
1170
996
  app.use(mw);
1171
997
  }
998
+ if (database) _chunkAZYXQU3Zcjs.setDbEngine.call(void 0, database);
999
+ _chunkAZYXQU3Zcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
1172
1000
  if (database === "mongodb" && databaseUrl) {
1173
- const conn = await connectMongo(databaseUrl);
1174
- setDbClient(conn);
1001
+ const conn = await _chunkAZYXQU3Zcjs.connectMongo.call(void 0, databaseUrl);
1002
+ _chunkAZYXQU3Zcjs.setDbClient.call(void 0, conn);
1003
+ } else if (database === "postgresql" && databaseUrl) {
1004
+ const pool = await _chunkMGH4VDV3cjs.connectPostgres.call(void 0, databaseUrl);
1005
+ _chunkAZYXQU3Zcjs.setDbClient.call(void 0, pool);
1006
+ }
1007
+ if (config.cache) {
1008
+ await _chunkZDM5JHVKcjs.configureCache.call(void 0, config.cache);
1175
1009
  }
1176
1010
  if (jwtSecret) {
1177
- _chunk6522HS2Jcjs.configureAuth.call(void 0, {
1011
+ _chunkZDM5JHVKcjs.configureAuth.call(void 0, {
1178
1012
  secret: jwtSecret,
1179
1013
  strategy: authStrategy,
1180
1014
  expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
@@ -1186,13 +1020,29 @@ async function ignite(config) {
1186
1020
  }
1187
1021
  if (config.tasks) {
1188
1022
  if (config.tasks.backend === "bullmq") {
1189
- await initBullMQ({
1023
+ await _chunkT4OHFU5Tcjs.initBullMQ.call(void 0, {
1190
1024
  redisUrl: _nullishCoalesce(config.tasks.redisUrl, () => ( "redis://localhost:6379")),
1191
- concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5))
1025
+ concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
1026
+ enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
1027
+ queue: _nullishCoalesce(config.tasks.queue, () => ( "efc"))
1028
+ });
1029
+ } else if (config.tasks.backend === "pg-boss") {
1030
+ const connectionString = _nullishCoalesce(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 _chunkTYR2GZZEcjs.initPgBoss.call(void 0, {
1037
+ connectionString,
1038
+ concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
1039
+ enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
1040
+ queue: _nullishCoalesce(config.tasks.queue, () => ( "efc")),
1041
+ ...config.tasks.schema !== void 0 && { schema: config.tasks.schema }
1192
1042
  });
1193
1043
  }
1194
1044
  }
1195
- const routes = _chunkDGVOJNR6cjs.scanDir.call(void 0, apiDir);
1045
+ const routes = _chunkR34R7QPDcjs.scanDir.call(void 0, apiDir);
1196
1046
  const apiRouter = _express2.default.Router();
1197
1047
  const mounted = await mountRoutes(apiRouter, routes);
1198
1048
  app.use(basePath, apiRouter);
@@ -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
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).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
- if (isHttpError(err)) {
1213
- res.status(err.statusCode).json({ error: err.message, statusCode: err.statusCode });
1066
+ if (_chunkAZYXQU3Zcjs.isHttpError.call(void 0, err)) {
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
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, "Unhandled error");
1218
1077
  res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
1219
1078
  }
1220
1079
  }
@@ -1223,33 +1082,40 @@ async function ignite(config) {
1223
1082
  return new Promise((resolve, reject) => {
1224
1083
  const server = app.listen(port);
1225
1084
  server.once("listening", () => {
1226
- const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _14 => _14.worker, 'optionalAccess', _15 => _15.id]), () => ( "primary"));
1085
+ const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _12 => _12.worker, 'optionalAccess', _13 => _13.id]), () => ( "primary"));
1227
1086
  const addr = server.address();
1228
- console.log(`[EFC] Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _16 => _16.port]), () => ( port))}`);
1087
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).info(`Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _14 => _14.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
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).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
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).info("Server closed");
1103
+ Promise.all([_chunkT4OHFU5Tcjs.closeBullMQ.call(void 0, ), _chunkTYR2GZZEcjs.closePgBoss.call(void 0, ), _chunkZDM5JHVKcjs.closeCache.call(void 0, )]).catch((err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1242
1104
  });
1243
1105
  setTimeout(() => {
1244
- console.error("[EFC] Forced exit after timeout");
1106
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
1245
1107
  process.exit(1);
1246
1108
  }, timeoutMs).unref();
1247
1109
  } else {
1248
1110
  shutdownMaster();
1111
+ setTimeout(() => {
1112
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).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
 
1255
1121
 
@@ -1264,5 +1130,12 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1264
1130
 
1265
1131
 
1266
1132
 
1267
- exports.HttpError = HttpError; exports.compose = compose; exports.db = db; exports.defineModel = defineModel; exports.getDbClient = getDbClient; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.scanDir = _chunkDGVOJNR6cjs.scanDir; exports.setDbClient = setDbClient; exports.workerCount = workerCount;
1133
+
1134
+
1135
+
1136
+
1137
+
1138
+
1139
+
1140
+ exports.HttpError = _chunkAZYXQU3Zcjs.HttpError; exports.ModelValidationError = _chunkAZYXQU3Zcjs.ModelValidationError; exports.cache = _chunkZDM5JHVKcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkAZYXQU3Zcjs.db; exports.defineModel = _chunkAZYXQU3Zcjs.defineModel; exports.defineTable = _chunkAZYXQU3Zcjs.defineTable; exports.getDbClient = _chunkAZYXQU3Zcjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkAZYXQU3Zcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkAZYXQU3Zcjs.setDbClient; exports.transaction = _chunkAZYXQU3Zcjs.transaction; exports.workerCount = workerCount;
1268
1141
  //# sourceMappingURL=index.cjs.map