express-file-cluster 0.3.14 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +204 -52
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
package/dist/index.cjs
CHANGED
|
@@ -2,16 +2,54 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
|
5
|
-
var _chunk6522HS2Jcjs = require('./chunk-6522HS2J.cjs');
|
|
6
5
|
|
|
7
6
|
|
|
7
|
+
var _chunkSFVEQ2T5cjs = require('./chunk-SFVEQ2T5.cjs');
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
var _chunkULQXD4YZcjs = require('./chunk-ULQXD4YZ.cjs');
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
var _chunkSZT36SGBcjs = require('./chunk-SZT36SGB.cjs');
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
var _chunkQTRGJ2ENcjs = require('./chunk-QTRGJ2EN.cjs');
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
var _chunkALBDM5R3cjs = require('./chunk-ALBDM5R3.cjs');
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
var _chunk47K2532Lcjs = require('./chunk-47K2532L.cjs');
|
|
40
|
+
require('./chunk-7YEX4MQV.cjs');
|
|
8
41
|
|
|
9
42
|
|
|
10
43
|
|
|
11
44
|
var _chunkTI24L4XEcjs = require('./chunk-TI24L4XE.cjs');
|
|
12
45
|
|
|
13
46
|
|
|
14
|
-
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
var _chunkRSBW2B3Dcjs = require('./chunk-RSBW2B3D.cjs');
|
|
15
53
|
|
|
16
54
|
// src/index.ts
|
|
17
55
|
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
@@ -22,6 +60,70 @@ var _cluster = require('cluster'); var _cluster2 = _interopRequireDefault(_clust
|
|
|
22
60
|
var _os = require('os'); var _os2 = _interopRequireDefault(_os);
|
|
23
61
|
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
24
62
|
|
|
63
|
+
// src/router/validate.ts
|
|
64
|
+
var LOCATIONS = ["params", "query", "body"];
|
|
65
|
+
function isRequestSchema(value) {
|
|
66
|
+
return value != null && typeof value === "object" && LOCATIONS.some((loc) => loc in value);
|
|
67
|
+
}
|
|
68
|
+
function schemaFor(schema, method) {
|
|
69
|
+
if (!schema) return void 0;
|
|
70
|
+
const byMethod = schema[method];
|
|
71
|
+
if (isRequestSchema(byMethod)) return byMethod;
|
|
72
|
+
return isRequestSchema(schema) ? schema : void 0;
|
|
73
|
+
}
|
|
74
|
+
function pathToString(path3) {
|
|
75
|
+
if (!path3) return "";
|
|
76
|
+
return path3.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).map(String).join(".");
|
|
77
|
+
}
|
|
78
|
+
async function run(validator, input) {
|
|
79
|
+
const std = validator["~standard"];
|
|
80
|
+
if (std && typeof std.validate === "function") {
|
|
81
|
+
return await std.validate(input);
|
|
82
|
+
}
|
|
83
|
+
const v = validator;
|
|
84
|
+
const parse = _nullishCoalesce(v.safeParseAsync, () => ( v.safeParse));
|
|
85
|
+
if (typeof parse !== "function") {
|
|
86
|
+
throw new Error("[EFC] Route schema entries must be Standard Schema validators (e.g. zod)");
|
|
87
|
+
}
|
|
88
|
+
const r = await parse.call(validator, input);
|
|
89
|
+
return r.success ? { value: r.data } : { issues: _nullishCoalesce(_optionalChain([r, 'access', _ => _.error, 'optionalAccess', _2 => _2.issues]), () => ( [{ message: "Invalid" }])) };
|
|
90
|
+
}
|
|
91
|
+
function validateRequest(schema) {
|
|
92
|
+
return (req, res, next) => {
|
|
93
|
+
void (async () => {
|
|
94
|
+
const issues = [];
|
|
95
|
+
const parsed = {};
|
|
96
|
+
for (const location of LOCATIONS) {
|
|
97
|
+
const validator = schema[location];
|
|
98
|
+
if (!validator) continue;
|
|
99
|
+
const result = await run(validator, req[location]);
|
|
100
|
+
if (result.issues) {
|
|
101
|
+
for (const issue of result.issues) {
|
|
102
|
+
issues.push({ location, path: pathToString(issue.path), message: issue.message });
|
|
103
|
+
}
|
|
104
|
+
} else {
|
|
105
|
+
parsed[location] = result.value;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (issues.length > 0) {
|
|
109
|
+
res.status(400).json({ error: "Validation failed", statusCode: 400, issues });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
for (const location of LOCATIONS) {
|
|
113
|
+
if (location in parsed) {
|
|
114
|
+
Object.defineProperty(req, location, {
|
|
115
|
+
value: parsed[location],
|
|
116
|
+
writable: true,
|
|
117
|
+
configurable: true,
|
|
118
|
+
enumerable: true
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
next();
|
|
123
|
+
})().catch(next);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
25
127
|
// src/router/mount.ts
|
|
26
128
|
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
27
129
|
function asyncWrap(handler) {
|
|
@@ -29,6 +131,25 @@ function asyncWrap(handler) {
|
|
|
29
131
|
Promise.resolve(handler(req, res, next)).catch(next);
|
|
30
132
|
};
|
|
31
133
|
}
|
|
134
|
+
function namedParams(route) {
|
|
135
|
+
const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
|
|
136
|
+
return (req, _res, next) => {
|
|
137
|
+
const positional = req.params;
|
|
138
|
+
const named = {};
|
|
139
|
+
route.params.forEach((name, i) => {
|
|
140
|
+
const value = positional[String(i)];
|
|
141
|
+
if (value === void 0 || value === "") {
|
|
142
|
+
named[name] = catchAlls.has(name) ? [] : void 0;
|
|
143
|
+
} else if (catchAlls.has(name)) {
|
|
144
|
+
named[name] = value.split("/").filter(Boolean).map(decodeURIComponent);
|
|
145
|
+
} else {
|
|
146
|
+
named[name] = decodeURIComponent(value);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
req.params = named;
|
|
150
|
+
next();
|
|
151
|
+
};
|
|
152
|
+
}
|
|
32
153
|
async function mountRoutes(app, routes) {
|
|
33
154
|
const mounted = [];
|
|
34
155
|
for (const route of routes) {
|
|
@@ -36,14 +157,21 @@ async function mountRoutes(app, routes) {
|
|
|
36
157
|
const routeMiddlewares = Array.isArray(mod["middlewares"]) ? mod["middlewares"] : [];
|
|
37
158
|
const raw = mod["meta"];
|
|
38
159
|
const meta = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
|
|
160
|
+
const schema = mod["schema"] != null && typeof mod["schema"] === "object" ? mod["schema"] : void 0;
|
|
161
|
+
const routePath = _nullishCoalesce(route.pattern, () => ( route.urlPath));
|
|
162
|
+
const paramMapper = route.pattern ? [namedParams(route)] : [];
|
|
39
163
|
const implemented = [];
|
|
40
164
|
const unimplemented = [];
|
|
41
165
|
for (const method of HTTP_METHODS) {
|
|
42
166
|
if (typeof mod[method] === "function") {
|
|
43
167
|
implemented.push(method);
|
|
168
|
+
const methodSchema = schemaFor(schema, method);
|
|
169
|
+
const validation = methodSchema ? [validateRequest(methodSchema)] : [];
|
|
44
170
|
app[method.toLowerCase()](
|
|
45
|
-
|
|
171
|
+
routePath,
|
|
172
|
+
...paramMapper,
|
|
46
173
|
...routeMiddlewares,
|
|
174
|
+
...validation,
|
|
47
175
|
asyncWrap(mod[method])
|
|
48
176
|
);
|
|
49
177
|
} else {
|
|
@@ -52,7 +180,7 @@ async function mountRoutes(app, routes) {
|
|
|
52
180
|
}
|
|
53
181
|
if (implemented.length > 0 && unimplemented.length > 0) {
|
|
54
182
|
const allowHeader = implemented.join(", ");
|
|
55
|
-
app.all(
|
|
183
|
+
app.all(routePath, (req, res, next) => {
|
|
56
184
|
if (unimplemented.includes(req.method)) {
|
|
57
185
|
res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
|
|
58
186
|
} else {
|
|
@@ -73,294 +201,37 @@ function workerCount() {
|
|
|
73
201
|
}
|
|
74
202
|
function shutdownMaster() {
|
|
75
203
|
isShuttingDown = true;
|
|
76
|
-
|
|
204
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
|
|
205
|
+
if (workerCount() === 0) process.exit(0);
|
|
206
|
+
for (const worker of Object.values(_nullishCoalesce(_cluster2.default.workers, () => ( {})))) {
|
|
207
|
+
_optionalChain([worker, 'optionalAccess', _3 => _3.process, 'access', _4 => _4.kill, 'call', _5 => _5("SIGTERM")]);
|
|
208
|
+
}
|
|
77
209
|
}
|
|
78
210
|
function runMaster(options = {}) {
|
|
79
211
|
const count = _nullishCoalesce(options.workers, () => ( 1));
|
|
80
|
-
|
|
212
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info(`Primary ${process.pid} starting ${count} workers`);
|
|
81
213
|
for (let i = 0; i < count; i++) {
|
|
82
214
|
_cluster2.default.fork();
|
|
83
215
|
}
|
|
84
216
|
_cluster2.default.on("online", (worker) => {
|
|
85
|
-
_optionalChain([options, 'access',
|
|
217
|
+
_optionalChain([options, 'access', _6 => _6.onWorkerReady, 'optionalCall', _7 => _7(worker.id)]);
|
|
86
218
|
});
|
|
87
219
|
_cluster2.default.on("exit", (worker, code, signal) => {
|
|
88
220
|
const exitCode = _nullishCoalesce(code, () => ( (signal ? -1 : 0)));
|
|
89
221
|
if (isShuttingDown) {
|
|
90
|
-
|
|
222
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info(`Worker ${worker.id} gracefully exited`);
|
|
91
223
|
if (workerCount() === 0) {
|
|
92
|
-
|
|
224
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info("All workers exited. Primary exiting.");
|
|
93
225
|
process.exit(0);
|
|
94
226
|
}
|
|
95
227
|
return;
|
|
96
228
|
}
|
|
97
|
-
|
|
98
|
-
_optionalChain([options, 'access',
|
|
229
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
|
|
230
|
+
_optionalChain([options, 'access', _8 => _8.onWorkerCrash, 'optionalCall', _9 => _9(worker.id, exitCode)]);
|
|
99
231
|
_cluster2.default.fork();
|
|
100
232
|
});
|
|
101
233
|
}
|
|
102
234
|
|
|
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
235
|
// src/tasks/scanner.ts
|
|
365
236
|
|
|
366
237
|
|
|
@@ -374,113 +245,17 @@ async function scanTasks(tasksDir) {
|
|
|
374
245
|
const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(filePath)));
|
|
375
246
|
const def = mod["default"];
|
|
376
247
|
if (!def || typeof def.handler !== "function") {
|
|
377
|
-
|
|
248
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).warn(`Task file ${file} has no valid default export \u2014 skipping`);
|
|
378
249
|
continue;
|
|
379
250
|
}
|
|
380
251
|
_chunkTI24L4XEcjs.registerTask.call(void 0, taskName, { ...def, filePath });
|
|
381
|
-
|
|
252
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).debug(`Registered task: ${taskName}`);
|
|
382
253
|
} catch (err) {
|
|
383
|
-
|
|
254
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).warn({ err }, `Failed to load task ${file}`);
|
|
384
255
|
}
|
|
385
256
|
}
|
|
386
257
|
}
|
|
387
258
|
|
|
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
259
|
// src/dashboard.ts
|
|
485
260
|
var HTTP_STATUS = {
|
|
486
261
|
200: "OK",
|
|
@@ -1079,6 +854,38 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
|
|
|
1079
854
|
</html>`;
|
|
1080
855
|
}
|
|
1081
856
|
|
|
857
|
+
// src/cache/response.ts
|
|
858
|
+
var RESPONSE_PREFIX = "res:";
|
|
859
|
+
function cacheResponse(options) {
|
|
860
|
+
const opts = typeof options === "number" ? { ttl: options } : options;
|
|
861
|
+
return (req, res, next) => {
|
|
862
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
863
|
+
let scope = "";
|
|
864
|
+
if (opts.perUser) {
|
|
865
|
+
const user = _chunkRSBW2B3Dcjs.getCurrentUser.call(void 0, );
|
|
866
|
+
const id = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _10 => _10["sub"]]), () => ( _optionalChain([user, 'optionalAccess', _11 => _11["id"]])));
|
|
867
|
+
if (id === void 0) return next();
|
|
868
|
+
scope = `u:${String(id)}:`;
|
|
869
|
+
}
|
|
870
|
+
const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
|
|
871
|
+
void (async () => {
|
|
872
|
+
const hit = await _chunkSFVEQ2T5cjs.cache.get(key);
|
|
873
|
+
if (hit) {
|
|
874
|
+
res.setHeader("X-Cache", "HIT");
|
|
875
|
+
res.status(hit.status).json(hit.body);
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
res.setHeader("X-Cache", "MISS");
|
|
879
|
+
const json = res.json.bind(res);
|
|
880
|
+
res.json = (body) => {
|
|
881
|
+
if (res.statusCode === 200) void _chunkSFVEQ2T5cjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
|
|
882
|
+
return json(body);
|
|
883
|
+
};
|
|
884
|
+
next();
|
|
885
|
+
})().catch(next);
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
|
|
1082
889
|
// src/compose.ts
|
|
1083
890
|
function compose(...handlers) {
|
|
1084
891
|
return (req, res, next) => {
|
|
@@ -1102,6 +909,29 @@ function compose(...handlers) {
|
|
|
1102
909
|
};
|
|
1103
910
|
}
|
|
1104
911
|
|
|
912
|
+
// src/db/transaction.ts
|
|
913
|
+
async function transaction(fn) {
|
|
914
|
+
if (_chunkQTRGJ2ENcjs.currentTx.call(void 0, )) return fn();
|
|
915
|
+
if (_chunkQTRGJ2ENcjs.getDbEngine.call(void 0, ) === "postgresql") {
|
|
916
|
+
let result;
|
|
917
|
+
await _chunkALBDM5R3cjs.getOrm.call(void 0, ).transaction(async (tx) => {
|
|
918
|
+
result = await _chunkQTRGJ2ENcjs.runInTx.call(void 0, { engine: "postgresql", tx }, fn);
|
|
919
|
+
});
|
|
920
|
+
return result;
|
|
921
|
+
}
|
|
922
|
+
const mg = await _chunkQTRGJ2ENcjs.loadMongoose.call(void 0, );
|
|
923
|
+
const session = await mg.connection.startSession();
|
|
924
|
+
try {
|
|
925
|
+
let result;
|
|
926
|
+
await session.withTransaction(async () => {
|
|
927
|
+
result = await _chunkQTRGJ2ENcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
|
|
928
|
+
});
|
|
929
|
+
return result;
|
|
930
|
+
} finally {
|
|
931
|
+
await session.endSession();
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
1105
935
|
// src/index.ts
|
|
1106
936
|
function detectDatabase(url) {
|
|
1107
937
|
if (!url) return void 0;
|
|
@@ -1135,7 +965,7 @@ async function ignite(config) {
|
|
|
1135
965
|
const raw = _fs2.default.readFileSync(_path2.default.join(process.cwd(), "package.json"), "utf8");
|
|
1136
966
|
const pkg = JSON.parse(raw);
|
|
1137
967
|
return { name: _nullishCoalesce(pkg.name, () => ( "API")), version: _nullishCoalesce(pkg.version, () => ( "")) };
|
|
1138
|
-
} catch (
|
|
968
|
+
} catch (e) {
|
|
1139
969
|
return { name: "API", version: "" };
|
|
1140
970
|
}
|
|
1141
971
|
}
|
|
@@ -1145,7 +975,11 @@ async function ignite(config) {
|
|
|
1145
975
|
const jwtSecret = config.jwtSecret;
|
|
1146
976
|
const authStrategy = _nullishCoalesce(config.authStrategy, () => ( "http-only"));
|
|
1147
977
|
const clusterEnabled = _nullishCoalesce(config.cluster, () => ( process.env["NODE_ENV"] === "production"));
|
|
978
|
+
_chunkRSBW2B3Dcjs.configureLogger.call(void 0, config.logging);
|
|
1148
979
|
if (clusterEnabled && _cluster2.default.isPrimary) {
|
|
980
|
+
if (config.cache && config.cache.backend === "memory") {
|
|
981
|
+
_chunkSFVEQ2T5cjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
|
|
982
|
+
}
|
|
1149
983
|
runMaster({
|
|
1150
984
|
workers: _nullishCoalesce(workers, () => ( _os2.default.cpus().length)),
|
|
1151
985
|
...onWorkerReady !== void 0 && { onWorkerReady },
|
|
@@ -1154,9 +988,26 @@ async function ignite(config) {
|
|
|
1154
988
|
return;
|
|
1155
989
|
}
|
|
1156
990
|
const app = _express2.default.call(void 0, );
|
|
991
|
+
app.set(
|
|
992
|
+
"json replacer",
|
|
993
|
+
(_key, value) => typeof value === "bigint" ? value.toString() : value
|
|
994
|
+
);
|
|
1157
995
|
app.use((_req, _res, next) => {
|
|
1158
|
-
|
|
996
|
+
_chunkRSBW2B3Dcjs.runWithContext.call(void 0, {}, next);
|
|
1159
997
|
});
|
|
998
|
+
app.use(_chunkRSBW2B3Dcjs.requestLogger.call(void 0, ));
|
|
999
|
+
if (config.requestTimeout) {
|
|
1000
|
+
const ms = config.requestTimeout;
|
|
1001
|
+
app.use((_req, res, next) => {
|
|
1002
|
+
const timer = setTimeout(() => {
|
|
1003
|
+
if (!res.headersSent) res.status(408).json({ error: "Request Timeout", statusCode: 408 });
|
|
1004
|
+
}, ms);
|
|
1005
|
+
const clear = () => clearTimeout(timer);
|
|
1006
|
+
res.once("finish", clear);
|
|
1007
|
+
res.once("close", clear);
|
|
1008
|
+
next();
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1160
1011
|
const corsOption = _nullishCoalesce(config.cors, () => ( true));
|
|
1161
1012
|
if (corsOption !== false) {
|
|
1162
1013
|
const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
|
|
@@ -1169,12 +1020,20 @@ async function ignite(config) {
|
|
|
1169
1020
|
for (const mw of globalMiddlewares) {
|
|
1170
1021
|
app.use(mw);
|
|
1171
1022
|
}
|
|
1023
|
+
if (database) _chunkQTRGJ2ENcjs.setDbEngine.call(void 0, database);
|
|
1024
|
+
_chunkQTRGJ2ENcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
|
|
1172
1025
|
if (database === "mongodb" && databaseUrl) {
|
|
1173
|
-
const conn = await connectMongo(databaseUrl);
|
|
1174
|
-
setDbClient(conn);
|
|
1026
|
+
const conn = await _chunkQTRGJ2ENcjs.connectMongo.call(void 0, databaseUrl);
|
|
1027
|
+
_chunkQTRGJ2ENcjs.setDbClient.call(void 0, conn);
|
|
1028
|
+
} else if (database === "postgresql" && databaseUrl) {
|
|
1029
|
+
const pool = await _chunkALBDM5R3cjs.connectPostgres.call(void 0, databaseUrl);
|
|
1030
|
+
_chunkQTRGJ2ENcjs.setDbClient.call(void 0, pool);
|
|
1031
|
+
}
|
|
1032
|
+
if (config.cache) {
|
|
1033
|
+
await _chunkSFVEQ2T5cjs.configureCache.call(void 0, config.cache);
|
|
1175
1034
|
}
|
|
1176
1035
|
if (jwtSecret) {
|
|
1177
|
-
|
|
1036
|
+
_chunkSFVEQ2T5cjs.configureAuth.call(void 0, {
|
|
1178
1037
|
secret: jwtSecret,
|
|
1179
1038
|
strategy: authStrategy,
|
|
1180
1039
|
expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
|
|
@@ -1186,13 +1045,29 @@ async function ignite(config) {
|
|
|
1186
1045
|
}
|
|
1187
1046
|
if (config.tasks) {
|
|
1188
1047
|
if (config.tasks.backend === "bullmq") {
|
|
1189
|
-
await initBullMQ({
|
|
1048
|
+
await _chunkSZT36SGBcjs.initBullMQ.call(void 0, {
|
|
1190
1049
|
redisUrl: _nullishCoalesce(config.tasks.redisUrl, () => ( "redis://localhost:6379")),
|
|
1191
|
-
concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5))
|
|
1050
|
+
concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
|
|
1051
|
+
enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
|
|
1052
|
+
queue: _nullishCoalesce(config.tasks.queue, () => ( "efc"))
|
|
1053
|
+
});
|
|
1054
|
+
} else if (config.tasks.backend === "pg-boss") {
|
|
1055
|
+
const connectionString = _nullishCoalesce(config.tasks.connectionString, () => ( databaseUrl));
|
|
1056
|
+
if (!connectionString) {
|
|
1057
|
+
throw new Error(
|
|
1058
|
+
'[EFC] tasks.backend "pg-boss" needs tasks.connectionString or databaseUrl'
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
await _chunk47K2532Lcjs.initPgBoss.call(void 0, {
|
|
1062
|
+
connectionString,
|
|
1063
|
+
concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
|
|
1064
|
+
enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
|
|
1065
|
+
queue: _nullishCoalesce(config.tasks.queue, () => ( "efc")),
|
|
1066
|
+
...config.tasks.schema !== void 0 && { schema: config.tasks.schema }
|
|
1192
1067
|
});
|
|
1193
1068
|
}
|
|
1194
1069
|
}
|
|
1195
|
-
const routes =
|
|
1070
|
+
const routes = _chunkULQXD4YZcjs.scanDir.call(void 0, apiDir);
|
|
1196
1071
|
const apiRouter = _express2.default.Router();
|
|
1197
1072
|
const mounted = await mountRoutes(apiRouter, routes);
|
|
1198
1073
|
app.use(basePath, apiRouter);
|
|
@@ -1208,13 +1083,22 @@ async function ignite(config) {
|
|
|
1208
1083
|
} else {
|
|
1209
1084
|
app.use(
|
|
1210
1085
|
(err, _req, res, _next) => {
|
|
1086
|
+
if (res.headersSent) {
|
|
1087
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).warn({ err }, "Error after the response was sent");
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1211
1090
|
const duckTyped = err instanceof Error && typeof err.statusCode === "number" ? err : null;
|
|
1212
|
-
if (isHttpError(err)) {
|
|
1213
|
-
|
|
1091
|
+
if (_chunkQTRGJ2ENcjs.isHttpError.call(void 0, err)) {
|
|
1092
|
+
const issues = err.issues;
|
|
1093
|
+
res.status(err.statusCode).json({
|
|
1094
|
+
error: err.message,
|
|
1095
|
+
statusCode: err.statusCode,
|
|
1096
|
+
...issues !== void 0 && { issues }
|
|
1097
|
+
});
|
|
1214
1098
|
} else if (duckTyped) {
|
|
1215
1099
|
res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
|
|
1216
1100
|
} else {
|
|
1217
|
-
|
|
1101
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).error({ err }, "Unhandled error");
|
|
1218
1102
|
res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
|
|
1219
1103
|
}
|
|
1220
1104
|
}
|
|
@@ -1223,33 +1107,40 @@ async function ignite(config) {
|
|
|
1223
1107
|
return new Promise((resolve, reject) => {
|
|
1224
1108
|
const server = app.listen(port);
|
|
1225
1109
|
server.once("listening", () => {
|
|
1226
|
-
const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access',
|
|
1110
|
+
const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _12 => _12.worker, 'optionalAccess', _13 => _13.id]), () => ( "primary"));
|
|
1227
1111
|
const addr = server.address();
|
|
1228
|
-
|
|
1112
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info(`Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _14 => _14.port]), () => ( port))}`);
|
|
1229
1113
|
resolve(server);
|
|
1230
1114
|
});
|
|
1231
1115
|
server.once("error", reject);
|
|
1232
1116
|
});
|
|
1233
1117
|
}
|
|
1234
1118
|
function gracefulShutdown(server, timeoutMs = 1e4) {
|
|
1119
|
+
let shuttingDown = false;
|
|
1235
1120
|
const shutdown = (signal) => {
|
|
1236
|
-
|
|
1121
|
+
if (shuttingDown) return;
|
|
1122
|
+
shuttingDown = true;
|
|
1123
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info(`${signal} received \u2014 closing server gracefully\u2026`);
|
|
1237
1124
|
if (server) {
|
|
1238
1125
|
server.closeIdleConnections();
|
|
1239
1126
|
server.close(() => {
|
|
1240
|
-
|
|
1241
|
-
process.exit(0);
|
|
1127
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info("Server closed");
|
|
1128
|
+
Promise.all([_chunkSZT36SGBcjs.closeBullMQ.call(void 0, ), _chunk47K2532Lcjs.closePgBoss.call(void 0, ), _chunkSFVEQ2T5cjs.closeCache.call(void 0, )]).catch((err) => _chunkRSBW2B3Dcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
|
|
1242
1129
|
});
|
|
1243
1130
|
setTimeout(() => {
|
|
1244
|
-
|
|
1131
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
|
|
1245
1132
|
process.exit(1);
|
|
1246
1133
|
}, timeoutMs).unref();
|
|
1247
1134
|
} else {
|
|
1248
1135
|
shutdownMaster();
|
|
1136
|
+
setTimeout(() => {
|
|
1137
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).error("Workers did not exit in time \u2014 forcing primary exit");
|
|
1138
|
+
process.exit(1);
|
|
1139
|
+
}, timeoutMs + 2e3).unref();
|
|
1249
1140
|
}
|
|
1250
1141
|
};
|
|
1251
|
-
process.
|
|
1252
|
-
process.
|
|
1142
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
1143
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
1253
1144
|
}
|
|
1254
1145
|
|
|
1255
1146
|
|
|
@@ -1264,5 +1155,12 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
|
|
|
1264
1155
|
|
|
1265
1156
|
|
|
1266
1157
|
|
|
1267
|
-
|
|
1158
|
+
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
exports.HttpError = _chunkQTRGJ2ENcjs.HttpError; exports.ModelValidationError = _chunkQTRGJ2ENcjs.ModelValidationError; exports.cache = _chunkSFVEQ2T5cjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkQTRGJ2ENcjs.db; exports.defineModel = _chunkQTRGJ2ENcjs.defineModel; exports.defineTable = _chunkQTRGJ2ENcjs.defineTable; exports.getDbClient = _chunkQTRGJ2ENcjs.getDbClient; exports.getLogger = _chunkRSBW2B3Dcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkQTRGJ2ENcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkRSBW2B3Dcjs.logger; exports.scanDir = _chunkULQXD4YZcjs.scanDir; exports.setDbClient = _chunkQTRGJ2ENcjs.setDbClient; exports.transaction = transaction; exports.workerCount = workerCount;
|
|
1268
1166
|
//# sourceMappingURL=index.cjs.map
|