express-file-cluster 0.3.5 → 0.3.7

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/dist/index.cjs CHANGED
@@ -95,6 +95,43 @@ function runMaster(options = {}) {
95
95
  });
96
96
  }
97
97
 
98
+ // src/errors.ts
99
+ var HttpError = class _HttpError extends Error {
100
+
101
+ constructor(statusCode, message) {
102
+ super(message);
103
+ this.name = "HttpError";
104
+ this.statusCode = statusCode;
105
+ Error.captureStackTrace(this, _HttpError);
106
+ }
107
+ /**
108
+ * Wraps an unknown caught value into an `HttpError`.
109
+ * If the value is already an `HttpError`, it is returned as-is.
110
+ * Otherwise the `message` from the caught `Error` (or a fallback) is used.
111
+ *
112
+ * @example
113
+ * } catch (err) {
114
+ * throw HttpError.from(err, 500, 'Something went wrong');
115
+ * }
116
+ */
117
+ static from(err, statusCode = 500, fallback = "Internal Server Error") {
118
+ if (err instanceof _HttpError) return err;
119
+ const message = err instanceof Error ? err.message : fallback;
120
+ return new _HttpError(statusCode, message);
121
+ }
122
+ /** Returns a plain object representation suitable for JSON serialization. */
123
+ toJSON() {
124
+ return {
125
+ statusCode: this.statusCode,
126
+ error: this.name,
127
+ message: this.message
128
+ };
129
+ }
130
+ };
131
+ function isHttpError(value) {
132
+ return value instanceof HttpError;
133
+ }
134
+
98
135
  // src/db/mongo.ts
99
136
  var mongoose;
100
137
  async function loadMongoose() {
@@ -118,7 +155,61 @@ function normalise(doc) {
118
155
  const id = doc["_id"] ? String(doc["_id"]) : "";
119
156
  return { ...doc, id };
120
157
  }
121
- async function getModel(name, schemaObj) {
158
+ function isNestedArraySchema(def) {
159
+ return Array.isArray(def);
160
+ }
161
+ function primitiveCtor(type, mg) {
162
+ switch (type) {
163
+ case "string":
164
+ return String;
165
+ case "number":
166
+ return Number;
167
+ case "boolean":
168
+ return Boolean;
169
+ case "date":
170
+ return Date;
171
+ case "object":
172
+ return Object;
173
+ case "objectId":
174
+ return mg.Schema.Types.ObjectId;
175
+ case "array":
176
+ return Array;
177
+ }
178
+ }
179
+ function buildFieldEntry(def, mg) {
180
+ const entry = {};
181
+ if (def.type === "array") {
182
+ if (def.of === "objectId") {
183
+ const item = { type: mg.Schema.Types.ObjectId };
184
+ if (def.ref !== void 0) item["ref"] = def.ref;
185
+ entry["type"] = [item];
186
+ } else if (def.of) {
187
+ entry["type"] = [primitiveCtor(def.of, mg)];
188
+ } else {
189
+ entry["type"] = Array;
190
+ }
191
+ } else {
192
+ entry["type"] = primitiveCtor(def.type, mg);
193
+ if (def.type === "objectId" && def.ref !== void 0) entry["ref"] = def.ref;
194
+ }
195
+ if (def.required !== void 0) entry["required"] = def.required;
196
+ if (def.unique !== void 0) entry["unique"] = def.unique;
197
+ if (def.default !== void 0) entry["default"] = def.default;
198
+ if (def.enum !== void 0) entry["enum"] = def.enum;
199
+ return entry;
200
+ }
201
+ function buildMongooseSchema(schema, mg) {
202
+ const out = {};
203
+ for (const [key, def] of Object.entries(schema)) {
204
+ if (isNestedArraySchema(def)) {
205
+ out[key] = def[0] ? [buildMongooseSchema(def[0], mg)] : [];
206
+ } else {
207
+ out[key] = buildFieldEntry(def, mg);
208
+ }
209
+ }
210
+ return out;
211
+ }
212
+ async function getModel(name, schema) {
122
213
  let mg;
123
214
  try {
124
215
  const mod = await Promise.resolve().then(() => _interopRequireWildcard(require("mongoose")));
@@ -127,77 +218,52 @@ async function getModel(name, schemaObj) {
127
218
  throw new Error("[EFC] mongoose is not installed. Run: npm install mongoose");
128
219
  }
129
220
  if (mg.models[name]) return mg.models[name];
130
- const schema = new mg.Schema(schemaObj, { timestamps: true });
131
- return mg.model(name, schema);
132
- }
133
- function buildMongooseSchema(schema) {
134
- const out = {};
135
- for (const [key, def] of Object.entries(schema)) {
136
- const entry = {};
137
- switch (def.type) {
138
- case "string":
139
- entry["type"] = String;
140
- break;
141
- case "number":
142
- entry["type"] = Number;
143
- break;
144
- case "boolean":
145
- entry["type"] = Boolean;
146
- break;
147
- case "date":
148
- entry["type"] = Date;
149
- break;
150
- case "object":
151
- entry["type"] = Object;
152
- break;
153
- case "array":
154
- entry["type"] = Array;
155
- break;
156
- }
157
- if (def.required !== void 0) entry["required"] = def.required;
158
- if (def.unique !== void 0) entry["unique"] = def.unique;
159
- if (def.default !== void 0) entry["default"] = def.default;
160
- out[key] = entry;
161
- }
162
- return out;
221
+ const schemaObj = buildMongooseSchema(schema, mg);
222
+ const mongooseSchema = new mg.Schema(schemaObj, { timestamps: true });
223
+ return mg.model(name, mongooseSchema);
163
224
  }
164
225
  function defineModel(name, schema) {
165
- const mongooseSchema = buildMongooseSchema(schema);
166
226
  return {
167
- async find(filter = {}) {
168
- const M = await getModel(name, mongooseSchema);
169
- const docs = await M.find(filter).lean();
227
+ async find(filter = {}, options) {
228
+ const M = await getModel(name, schema);
229
+ const query = M.find(filter);
230
+ if (_optionalChain([options, 'optionalAccess', _5 => _5.populate])) query.populate(options.populate);
231
+ const docs = await query.lean();
170
232
  return docs.map(normalise);
171
233
  },
172
- async findById(id) {
173
- const M = await getModel(name, mongooseSchema);
174
- const doc = await M.findById(id).lean();
234
+ async findById(id, options) {
235
+ const M = await getModel(name, schema);
236
+ const query = M.findById(id);
237
+ if (_optionalChain([options, 'optionalAccess', _6 => _6.populate])) query.populate(options.populate);
238
+ const doc = await query.lean();
175
239
  if (!doc) return null;
176
240
  return normalise(doc);
177
241
  },
178
- async findOne(filter) {
179
- const M = await getModel(name, mongooseSchema);
180
- const doc = await M.findOne(filter).lean();
242
+ async findOne(filter, options) {
243
+ const M = await getModel(name, schema);
244
+ const query = M.findOne(filter);
245
+ if (_optionalChain([options, 'optionalAccess', _7 => _7.populate])) query.populate(options.populate);
246
+ const doc = await query.lean();
181
247
  if (!doc) return null;
182
248
  return normalise(doc);
183
249
  },
184
250
  async create(data) {
185
- const M = await getModel(name, mongooseSchema);
251
+ const M = await getModel(name, schema);
186
252
  const doc = await M.create(data);
187
253
  return normalise(doc.toObject());
188
254
  },
189
255
  async update(id, data) {
190
- const M = await getModel(name, mongooseSchema);
256
+ const M = await getModel(name, schema);
191
257
  const doc = await M.findByIdAndUpdate(id, data, { new: true }).lean();
192
258
  if (!doc) return null;
193
259
  return normalise(doc);
194
260
  },
195
261
  async delete(id) {
196
- const M = await getModel(name, mongooseSchema);
262
+ const M = await getModel(name, schema);
197
263
  await M.findByIdAndDelete(id);
198
264
  },
199
265
  async count(filter = {}) {
200
- const M = await getModel(name, mongooseSchema);
266
+ const M = await getModel(name, schema);
201
267
  return M.countDocuments(filter);
202
268
  }
203
269
  };
@@ -260,9 +326,9 @@ if (!_worker_threads.isMainThread) {
260
326
  throw new Error(`[EFC] Thread runner: no valid task export in ${handlerPath}`);
261
327
  }
262
328
  await def.handler(payload);
263
- _optionalChain([_worker_threads.parentPort, 'optionalAccess', _5 => _5.postMessage, 'call', _6 => _6({ ok: true })]);
329
+ _optionalChain([_worker_threads.parentPort, 'optionalAccess', _8 => _8.postMessage, 'call', _9 => _9({ ok: true })]);
264
330
  } catch (err) {
265
- _optionalChain([_worker_threads.parentPort, 'optionalAccess', _7 => _7.postMessage, 'call', _8 => _8({ ok: false, error: String(err) })]);
331
+ _optionalChain([_worker_threads.parentPort, 'optionalAccess', _10 => _10.postMessage, 'call', _11 => _11({ ok: false, error: String(err) })]);
266
332
  }
267
333
  })();
268
334
  }
@@ -308,7 +374,7 @@ async function initBullMQ(opts) {
308
374
  { connection, concurrency: opts.concurrency }
309
375
  );
310
376
  worker.on("failed", (job, err) => {
311
- console.error(`[EFC] Task ${_nullishCoalesce(_optionalChain([job, 'optionalAccess', _9 => _9.name]), () => ( "unknown"))} failed:`, err.message);
377
+ console.error(`[EFC] Task ${_nullishCoalesce(_optionalChain([job, 'optionalAccess', _12 => _12.name]), () => ( "unknown"))} failed:`, err.message);
312
378
  });
313
379
  worker.on("completed", (job) => {
314
380
  console.log(`[EFC] Task ${job.name} completed (id=${job.id})`);
@@ -942,25 +1008,6 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
942
1008
  </html>`;
943
1009
  }
944
1010
 
945
- // src/errors.ts
946
- var HttpError = class _HttpError extends Error {
947
-
948
- constructor(statusCode, message) {
949
- super(message);
950
- this.name = "HttpError";
951
- this.statusCode = statusCode;
952
- Error.captureStackTrace(this, _HttpError);
953
- }
954
- /** Returns a plain object representation suitable for JSON serialization. */
955
- toJSON() {
956
- return {
957
- statusCode: this.statusCode,
958
- error: this.name,
959
- message: this.message
960
- };
961
- }
962
- };
963
-
964
1011
  // src/compose.ts
965
1012
  function compose(...handlers) {
966
1013
  return (req, res, next) => {
@@ -1021,11 +1068,10 @@ async function ignite(config) {
1021
1068
  return { name: "API", version: "" };
1022
1069
  }
1023
1070
  }
1024
- const envPort = process.env["PORT"] != null ? Number(process.env["PORT"]) : NaN;
1025
- const port = _port != null && !Number.isNaN(_port) ? _port : !Number.isNaN(envPort) ? envPort : 3e3;
1026
- const databaseUrl = _nullishCoalesce(config.databaseUrl, () => ( process.env["DATABASE_URL"]));
1071
+ const port = _port != null && !Number.isNaN(_port) ? _port : 3e3;
1072
+ const databaseUrl = config.databaseUrl;
1027
1073
  const database = _nullishCoalesce(config.database, () => ( detectDatabase(databaseUrl)));
1028
- const jwtSecret = _nullishCoalesce(config.jwtSecret, () => ( process.env["JWT_SECRET"]));
1074
+ const jwtSecret = config.jwtSecret;
1029
1075
  const authStrategy = _nullishCoalesce(config.authStrategy, () => ( "http-only"));
1030
1076
  const clusterEnabled = _nullishCoalesce(config.cluster, () => ( process.env["NODE_ENV"] === "production"));
1031
1077
  if (clusterEnabled && _cluster2.default.isPrimary) {
@@ -1039,16 +1085,7 @@ async function ignite(config) {
1039
1085
  const app = _express2.default.call(void 0, );
1040
1086
  const corsOption = _nullishCoalesce(config.cors, () => ( true));
1041
1087
  if (corsOption !== false) {
1042
- const envOrigins = process.env["CORS_ORIGINS"];
1043
- let origin;
1044
- if (envOrigins) {
1045
- const list = envOrigins.split(",").map((o) => o.trim()).filter(Boolean);
1046
- origin = list;
1047
- } else if (typeof corsOption === "object" && corsOption.origin !== void 0) {
1048
- origin = corsOption.origin;
1049
- } else {
1050
- origin = true;
1051
- }
1088
+ const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
1052
1089
  const corsOpts = typeof corsOption === "object" ? { ...corsOption, origin } : { origin };
1053
1090
  app.use(_cors2.default.call(void 0, corsOpts));
1054
1091
  }
@@ -1063,12 +1100,11 @@ async function ignite(config) {
1063
1100
  setDbClient(conn);
1064
1101
  }
1065
1102
  if (jwtSecret) {
1066
- const cookieDomain = process.env["COOKIE_DOMAIN"];
1067
1103
  _chunkQOKLEPTXcjs.configureAuth.call(void 0, {
1068
1104
  secret: jwtSecret,
1069
1105
  strategy: authStrategy,
1070
- expiresIn: _nullishCoalesce(process.env["JWT_EXPIRES_IN"], () => ( "7d")),
1071
- ...cookieDomain !== void 0 && { cookieDomain }
1106
+ expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
1107
+ ...config.cookieDomain !== void 0 && { cookieDomain: config.cookieDomain }
1072
1108
  });
1073
1109
  }
1074
1110
  if (tasksDir) {
@@ -1098,9 +1134,8 @@ async function ignite(config) {
1098
1134
  } else {
1099
1135
  app.use(
1100
1136
  (err, _req, res, _next) => {
1101
- const asHttp = err instanceof Error && "statusCode" in err ? err : null;
1102
- if (asHttp) {
1103
- res.status(asHttp.statusCode).json({ error: asHttp.message, statusCode: asHttp.statusCode });
1137
+ if (isHttpError(err)) {
1138
+ res.status(err.statusCode).json({ error: err.message, statusCode: err.statusCode });
1104
1139
  } else {
1105
1140
  console.error("[EFC] Unhandled error:", err);
1106
1141
  res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
@@ -1111,9 +1146,9 @@ async function ignite(config) {
1111
1146
  return new Promise((resolve, reject) => {
1112
1147
  const server = app.listen(port);
1113
1148
  server.once("listening", () => {
1114
- const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _10 => _10.worker, 'optionalAccess', _11 => _11.id]), () => ( "primary"));
1149
+ const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _13 => _13.worker, 'optionalAccess', _14 => _14.id]), () => ( "primary"));
1115
1150
  const addr = server.address();
1116
- console.log(`[EFC] Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _12 => _12.port]), () => ( port))}`);
1151
+ console.log(`[EFC] Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _15 => _15.port]), () => ( port))}`);
1117
1152
  resolve(server);
1118
1153
  });
1119
1154
  server.once("error", reject);
@@ -1149,5 +1184,6 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1149
1184
 
1150
1185
 
1151
1186
 
1152
- exports.HttpError = HttpError; exports.compose = compose; exports.db = db; exports.defineModel = defineModel; exports.getDbClient = getDbClient; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.scanDir = _chunkMQNVNOH5cjs.scanDir; exports.setDbClient = setDbClient;
1187
+
1188
+ 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.scanDir = _chunkMQNVNOH5cjs.scanDir; exports.setDbClient = setDbClient;
1153
1189
  //# sourceMappingURL=index.cjs.map