cynx-lib 1.3.115 → 1.3.116
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/gen.js +77 -77
- package/package.json +1 -1
- package/ui/components/ActionsMenu.jsx +357 -357
- package/ui/components/BrandingCard.jsx +6 -6
- package/ui/components/Drawer.jsx +208 -208
- package/ui/components/Globe.jsx +764 -764
- package/ui/components/HoverCard.jsx +85 -85
- package/ui/components/PrivacyBlur.jsx +603 -603
- package/utils/index.js +24 -24
- package/utils/utils/duration.js +139 -139
- package/utils/utils/oidc.js +214 -214
- package/utils/utils/realtime.js +1634 -1634
- package/utils/utils/server.js +371 -371
- package/utils/utils/session.js +131 -131
- package/utils/utils/session_manager.js +580 -580
- package/utils/utils/sso_manager.js +702 -702
- package/utils/utils/storage.js +393 -393
- package/utils/utils/ui.js +111 -111
- package/vue/components/Badge.vue +79 -79
- package/vue/components/Button.vue +209 -209
- package/vue/components/Checkbox.vue +103 -103
- package/vue/components/CircularProgress.vue +383 -383
- package/vue/components/Divider.vue +94 -94
- package/vue/components/Drawer.vue +243 -243
- package/vue/components/InfoBadge.vue +223 -223
- package/vue/components/Input.vue +341 -341
- package/vue/components/LinearProgress.vue +268 -268
- package/vue/components/Modal.vue +226 -226
- package/vue/components/Pagination.vue +199 -199
- package/vue/components/Select.vue +713 -713
- package/vue/components/Sidebar.vue +955 -955
- package/vue/components/Skeleton.vue +91 -91
- package/vue/components/Spinner.vue +263 -263
- package/vue/components/StatusTag.vue +89 -89
- package/vue/components/TabBar.vue +176 -176
- package/vue/components/Table.vue +393 -393
- package/vue/components/TimePicker.vue +399 -399
- package/vue/components/Toggle.vue +115 -115
- package/vue/components/XTable.vue +140 -140
- package/vue/composables/useAutoSkeletonRows.ts +71 -71
- package/vue/index.d.ts +67 -67
- package/vue/index.js +86 -86
package/utils/utils/server.js
CHANGED
|
@@ -1,371 +1,371 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* cynx/server — Universal Microservice & HTTP Server Engine (server.js)
|
|
3
|
-
*
|
|
4
|
-
* Provides a standardized, zero-boilerplate Node.js / Express server runner:
|
|
5
|
-
* - Automatic route discovery and declarative mounting from routes directory
|
|
6
|
-
* - Standardized start-up banner with commit info, timing, and network IP
|
|
7
|
-
* - Git commit & build info extraction (app_commit, app_build_info)
|
|
8
|
-
* - Preconfigured middleware: CORS, Compression, Body parsers with limits
|
|
9
|
-
* - Lifecycle hooks (beforeRoutes, beforeErrorHandler, onStart)
|
|
10
|
-
* - Resilience settings (keepAliveTimeout, headersTimeout, process error catchers)
|
|
11
|
-
* - Built-in /api/health endpoint
|
|
12
|
-
*
|
|
13
|
-
* STRICT NO EMOJIS!
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import fs from 'fs';
|
|
17
|
-
import path from 'path';
|
|
18
|
-
import os from 'os';
|
|
19
|
-
import http from 'http';
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
let cachedCommit = null;
|
|
23
|
-
let cachedBuildInfo = null;
|
|
24
|
-
const bootTime = new Date().toISOString();
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Execute git command safely with timeout.
|
|
28
|
-
*/
|
|
29
|
-
export function execGit(cmd, cwd) {
|
|
30
|
-
try {
|
|
31
|
-
const execSyncFn = typeof require !== 'undefined' ? require('child_process').execSync : null;
|
|
32
|
-
if (!execSyncFn) return '';
|
|
33
|
-
const stdout = execSyncFn(cmd, {
|
|
34
|
-
cwd: cwd || process.cwd(),
|
|
35
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
36
|
-
timeout: 2000,
|
|
37
|
-
encoding: 'utf8',
|
|
38
|
-
});
|
|
39
|
-
return stdout ? stdout.trim() : '';
|
|
40
|
-
} catch {
|
|
41
|
-
return '';
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Get current git commit hash (short 7-char).
|
|
47
|
-
*/
|
|
48
|
-
export function app_commit(cwd) {
|
|
49
|
-
if (cachedCommit !== null) {
|
|
50
|
-
return cachedCommit;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
if (process.env.APP_COMMIT && process.env.APP_COMMIT.trim()) {
|
|
54
|
-
cachedCommit = process.env.APP_COMMIT.trim();
|
|
55
|
-
return cachedCommit;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (process.env.GIT_COMMIT && process.env.GIT_COMMIT.trim()) {
|
|
59
|
-
cachedCommit = process.env.GIT_COMMIT.trim().slice(0, 7);
|
|
60
|
-
return cachedCommit;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
cachedCommit = execGit('git rev-parse --short HEAD', cwd);
|
|
64
|
-
return cachedCommit;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Get application build and git metadata.
|
|
69
|
-
*/
|
|
70
|
-
export function app_build_info(cwd) {
|
|
71
|
-
if (cachedBuildInfo !== null) {
|
|
72
|
-
return cachedBuildInfo;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const commit = app_commit(cwd);
|
|
76
|
-
|
|
77
|
-
const branch =
|
|
78
|
-
(process.env.APP_BRANCH && process.env.APP_BRANCH.trim()) ||
|
|
79
|
-
(process.env.GIT_BRANCH && process.env.GIT_BRANCH.trim()) ||
|
|
80
|
-
execGit('git rev-parse --abbrev-ref HEAD', cwd) ||
|
|
81
|
-
'main';
|
|
82
|
-
|
|
83
|
-
const rawDate =
|
|
84
|
-
(process.env.APP_COMMIT_DATE && process.env.APP_COMMIT_DATE.trim()) ||
|
|
85
|
-
execGit('git log -1 --format=%ci', cwd);
|
|
86
|
-
const commitDate = rawDate ? rawDate.slice(0, 16) : '';
|
|
87
|
-
|
|
88
|
-
const buildTime =
|
|
89
|
-
(process.env.BUILD_TIME && process.env.BUILD_TIME.trim()) ||
|
|
90
|
-
bootTime;
|
|
91
|
-
|
|
92
|
-
cachedBuildInfo = {
|
|
93
|
-
commit,
|
|
94
|
-
branch,
|
|
95
|
-
commitDate,
|
|
96
|
-
buildTime,
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
return cachedBuildInfo;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Resolve local network IPv4 address.
|
|
104
|
-
*/
|
|
105
|
-
export function getNetworkIp() {
|
|
106
|
-
try {
|
|
107
|
-
const interfaces = os.networkInterfaces();
|
|
108
|
-
for (const name of Object.keys(interfaces)) {
|
|
109
|
-
for (const iface of interfaces[name]) {
|
|
110
|
-
if (iface.family === 'IPv4' && !iface.internal) {
|
|
111
|
-
return iface.address;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
} catch {
|
|
116
|
-
// fallback
|
|
117
|
-
}
|
|
118
|
-
return null;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Print standardized start-up banner.
|
|
123
|
-
*/
|
|
124
|
-
export function printServerBanner({
|
|
125
|
-
port,
|
|
126
|
-
elapsed,
|
|
127
|
-
commit,
|
|
128
|
-
shouldSyncDb = false,
|
|
129
|
-
isSynced = false,
|
|
130
|
-
networkIp = undefined,
|
|
131
|
-
}) {
|
|
132
|
-
const commitTag = commit ? ' \x1b[32m' + commit + '\x1b[0m' : '';
|
|
133
|
-
const resolvedIp = (networkIp !== undefined && networkIp !== null) ? networkIp : getNetworkIp();
|
|
134
|
-
|
|
135
|
-
console.log('\n \x1b[32m\x1b[1mSERVER\x1b[0m' + commitTag + ' \x1b[90mready in ' + elapsed + ' ms\x1b[0m\n');
|
|
136
|
-
console.log(' \x1b[32m➜\x1b[0m \x1b[1mLocal:\x1b[0m \x1b[36mhttp://localhost:' + port + '/\x1b[0m');
|
|
137
|
-
if (resolvedIp) {
|
|
138
|
-
console.log(' \x1b[32m➜\x1b[0m \x1b[1mNetwork:\x1b[0m \x1b[36mhttp://' + resolvedIp + ':' + port + '/\x1b[0m');
|
|
139
|
-
}
|
|
140
|
-
const dbStatus = isSynced
|
|
141
|
-
? '\x1b[32mSynced\x1b[0m'
|
|
142
|
-
: '\x1b[90mSkipped (pass -s to sync)\x1b[0m';
|
|
143
|
-
console.log(' \x1b[32m➜\x1b[0m \x1b[1mDatabase:\x1b[0m ' + dbStatus + '\n');
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Helper to create a router with route metadata.
|
|
148
|
-
*/
|
|
149
|
-
export function createRouter(options = {}) {
|
|
150
|
-
const expressModule = options.express || (typeof require !== 'undefined' ? require('express') : null);
|
|
151
|
-
if (!expressModule) {
|
|
152
|
-
throw new Error('[cynx/server] express is required to use createRouter');
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
const router = expressModule.Router(options.routerOptions || {});
|
|
156
|
-
if (options.prefix) {
|
|
157
|
-
router._cynxPrefix = options.prefix;
|
|
158
|
-
}
|
|
159
|
-
return router;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Auto-discover and mount routes from a directory.
|
|
164
|
-
*/
|
|
165
|
-
export function loadRoutes(app, routesDir, options = {}) {
|
|
166
|
-
if (!routesDir || !fs.existsSync(routesDir)) {
|
|
167
|
-
return [];
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const customPrefixes = options.routePrefixes || {};
|
|
171
|
-
const mounted = [];
|
|
172
|
-
const files = fs.readdirSync(routesDir);
|
|
173
|
-
|
|
174
|
-
for (const file of files) {
|
|
175
|
-
const ext = path.extname(file);
|
|
176
|
-
if (!['.js', '.cjs', '.mjs'].includes(ext)) continue;
|
|
177
|
-
if (file.startsWith('.') || file.startsWith('_')) continue;
|
|
178
|
-
|
|
179
|
-
const baseName = path.basename(file, ext);
|
|
180
|
-
const fullPath = path.resolve(routesDir, file);
|
|
181
|
-
|
|
182
|
-
let routeModule;
|
|
183
|
-
try {
|
|
184
|
-
routeModule = typeof require !== 'undefined' ? require(fullPath) : null;
|
|
185
|
-
} catch (err) {
|
|
186
|
-
console.error(`[cynx/server] Error loading route file ${file}:`, err);
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
if (!routeModule) continue;
|
|
191
|
-
|
|
192
|
-
const router = routeModule.default || routeModule.router || routeModule;
|
|
193
|
-
if (typeof router !== 'function' && (!router || typeof router.use !== 'function')) {
|
|
194
|
-
continue;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// Determine mount prefix(es)
|
|
198
|
-
let prefixes = router._cynxPrefix || router.prefix || customPrefixes[baseName];
|
|
199
|
-
if (!prefixes) {
|
|
200
|
-
prefixes = `/api/${baseName}`;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const prefixList = Array.isArray(prefixes) ? prefixes : [prefixes];
|
|
204
|
-
for (const prefix of prefixList) {
|
|
205
|
-
app.use(prefix, router);
|
|
206
|
-
mounted.push({ file, prefix });
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
return mounted;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Create and configure standardized Express application and HTTP server.
|
|
215
|
-
*/
|
|
216
|
-
export function createServer(options = {}) {
|
|
217
|
-
const expressModule = options.express || (typeof require !== 'undefined' ? require('express') : null);
|
|
218
|
-
if (!expressModule) {
|
|
219
|
-
throw new Error('[cynx/server] express is required to create a server');
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
const app = options.app || expressModule();
|
|
223
|
-
const startTime = Date.now();
|
|
224
|
-
|
|
225
|
-
// 1. CORS
|
|
226
|
-
if (options.cors !== false) {
|
|
227
|
-
const corsModule = options.corsMiddleware || (typeof require !== 'undefined' ? require('cors') : null);
|
|
228
|
-
if (corsModule) {
|
|
229
|
-
app.use(typeof options.cors === 'object' ? corsModule(options.cors) : corsModule());
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// 2. Compression
|
|
234
|
-
if (options.compression) {
|
|
235
|
-
if (typeof options.compression === 'function') {
|
|
236
|
-
app.use(options.compression);
|
|
237
|
-
} else {
|
|
238
|
-
const compModule = typeof require !== 'undefined' ? require('compression') : null;
|
|
239
|
-
if (compModule) app.use(compModule());
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// 3. Body Parsers
|
|
244
|
-
const limit = options.bodyLimit || '5mb';
|
|
245
|
-
app.use(expressModule.json({ limit }));
|
|
246
|
-
app.use(expressModule.urlencoded({ extended: true, limit }));
|
|
247
|
-
|
|
248
|
-
// 4. Hook before routes (custom loggers, metrics, etc.)
|
|
249
|
-
if (typeof options.beforeRoutes === 'function') {
|
|
250
|
-
options.beforeRoutes(app);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// 5. Auto-mount routes
|
|
254
|
-
if (options.routesDir) {
|
|
255
|
-
loadRoutes(app, options.routesDir, options);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// 6. Explicit routes list
|
|
259
|
-
if (Array.isArray(options.routes)) {
|
|
260
|
-
for (const route of options.routes) {
|
|
261
|
-
if (route.prefix && route.router) {
|
|
262
|
-
const list = Array.isArray(route.prefix) ? route.prefix : [route.prefix];
|
|
263
|
-
for (const p of list) {
|
|
264
|
-
app.use(p, route.router);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// 7. Built-in healthcheck
|
|
271
|
-
if (options.healthcheck !== false) {
|
|
272
|
-
app.get('/api/health', (_req, res) => res.json({ status: 'ok' }));
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// 8. Hook before error handler (e.g. Sentry.setupExpressErrorHandler)
|
|
276
|
-
if (typeof options.beforeErrorHandler === 'function') {
|
|
277
|
-
options.beforeErrorHandler(app);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// 9. Standardized JSON Error Handler
|
|
281
|
-
if (options.errorHandler !== false) {
|
|
282
|
-
app.use((err, _req, res, _next) => {
|
|
283
|
-
console.error('[HTTP]', err);
|
|
284
|
-
res.status(err.status || 500).json({ error: err.message || 'Internal server error' });
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// 10. Process level unhandled error safety
|
|
289
|
-
if (options.processHandlers !== false) {
|
|
290
|
-
process.on('unhandledRejection', (reason) => {
|
|
291
|
-
console.error('[System]', reason);
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
process.on('uncaughtException', (err) => {
|
|
295
|
-
console.error('[System]', err);
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
const port = options.port || process.env.BACKEND_PORT || process.env.PORT || 3000;
|
|
300
|
-
const host = options.host || '0.0.0.0';
|
|
301
|
-
let httpServer = null;
|
|
302
|
-
|
|
303
|
-
return {
|
|
304
|
-
app,
|
|
305
|
-
get httpServer() {
|
|
306
|
-
return httpServer;
|
|
307
|
-
},
|
|
308
|
-
port,
|
|
309
|
-
host,
|
|
310
|
-
start: function (onReady) {
|
|
311
|
-
return new Promise((resolve, reject) => {
|
|
312
|
-
try {
|
|
313
|
-
httpServer = app.listen(port, host, async () => {
|
|
314
|
-
const elapsed = Date.now() - startTime;
|
|
315
|
-
const build = app_build_info();
|
|
316
|
-
|
|
317
|
-
// Print banner if not disabled
|
|
318
|
-
if (options.banner !== false) {
|
|
319
|
-
printServerBanner({
|
|
320
|
-
port,
|
|
321
|
-
elapsed,
|
|
322
|
-
commit: build.commit,
|
|
323
|
-
shouldSyncDb: options.shouldSyncDb,
|
|
324
|
-
isSynced: options.isSynced,
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
if (typeof options.onStart === 'function') {
|
|
329
|
-
try {
|
|
330
|
-
await options.onStart({ app, httpServer, port, host, elapsed, build });
|
|
331
|
-
} catch (onStartErr) {
|
|
332
|
-
console.error('[cynx/server] onStart error:', onStartErr);
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
if (typeof onReady === 'function') {
|
|
337
|
-
onReady({ app, httpServer, port, host, elapsed, build });
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
resolve({ app, httpServer, port, host, elapsed, build });
|
|
341
|
-
});
|
|
342
|
-
|
|
343
|
-
httpServer.keepAliveTimeout = options.keepAliveTimeout || 65000;
|
|
344
|
-
httpServer.headersTimeout = options.headersTimeout || 66000;
|
|
345
|
-
} catch (listenErr) {
|
|
346
|
-
reject(listenErr);
|
|
347
|
-
}
|
|
348
|
-
});
|
|
349
|
-
},
|
|
350
|
-
stop: function () {
|
|
351
|
-
return new Promise((resolve) => {
|
|
352
|
-
if (httpServer) {
|
|
353
|
-
httpServer.close(() => resolve());
|
|
354
|
-
} else {
|
|
355
|
-
resolve();
|
|
356
|
-
}
|
|
357
|
-
});
|
|
358
|
-
},
|
|
359
|
-
};
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
export default {
|
|
363
|
-
createServer,
|
|
364
|
-
createRouter,
|
|
365
|
-
loadRoutes,
|
|
366
|
-
app_commit,
|
|
367
|
-
app_build_info,
|
|
368
|
-
printServerBanner,
|
|
369
|
-
getNetworkIp,
|
|
370
|
-
execGit,
|
|
371
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* cynx/server — Universal Microservice & HTTP Server Engine (server.js)
|
|
3
|
+
*
|
|
4
|
+
* Provides a standardized, zero-boilerplate Node.js / Express server runner:
|
|
5
|
+
* - Automatic route discovery and declarative mounting from routes directory
|
|
6
|
+
* - Standardized start-up banner with commit info, timing, and network IP
|
|
7
|
+
* - Git commit & build info extraction (app_commit, app_build_info)
|
|
8
|
+
* - Preconfigured middleware: CORS, Compression, Body parsers with limits
|
|
9
|
+
* - Lifecycle hooks (beforeRoutes, beforeErrorHandler, onStart)
|
|
10
|
+
* - Resilience settings (keepAliveTimeout, headersTimeout, process error catchers)
|
|
11
|
+
* - Built-in /api/health endpoint
|
|
12
|
+
*
|
|
13
|
+
* STRICT NO EMOJIS!
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'fs';
|
|
17
|
+
import path from 'path';
|
|
18
|
+
import os from 'os';
|
|
19
|
+
import http from 'http';
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
let cachedCommit = null;
|
|
23
|
+
let cachedBuildInfo = null;
|
|
24
|
+
const bootTime = new Date().toISOString();
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Execute git command safely with timeout.
|
|
28
|
+
*/
|
|
29
|
+
export function execGit(cmd, cwd) {
|
|
30
|
+
try {
|
|
31
|
+
const execSyncFn = typeof require !== 'undefined' ? require('child_process').execSync : null;
|
|
32
|
+
if (!execSyncFn) return '';
|
|
33
|
+
const stdout = execSyncFn(cmd, {
|
|
34
|
+
cwd: cwd || process.cwd(),
|
|
35
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
36
|
+
timeout: 2000,
|
|
37
|
+
encoding: 'utf8',
|
|
38
|
+
});
|
|
39
|
+
return stdout ? stdout.trim() : '';
|
|
40
|
+
} catch {
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Get current git commit hash (short 7-char).
|
|
47
|
+
*/
|
|
48
|
+
export function app_commit(cwd) {
|
|
49
|
+
if (cachedCommit !== null) {
|
|
50
|
+
return cachedCommit;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (process.env.APP_COMMIT && process.env.APP_COMMIT.trim()) {
|
|
54
|
+
cachedCommit = process.env.APP_COMMIT.trim();
|
|
55
|
+
return cachedCommit;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (process.env.GIT_COMMIT && process.env.GIT_COMMIT.trim()) {
|
|
59
|
+
cachedCommit = process.env.GIT_COMMIT.trim().slice(0, 7);
|
|
60
|
+
return cachedCommit;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
cachedCommit = execGit('git rev-parse --short HEAD', cwd);
|
|
64
|
+
return cachedCommit;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Get application build and git metadata.
|
|
69
|
+
*/
|
|
70
|
+
export function app_build_info(cwd) {
|
|
71
|
+
if (cachedBuildInfo !== null) {
|
|
72
|
+
return cachedBuildInfo;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const commit = app_commit(cwd);
|
|
76
|
+
|
|
77
|
+
const branch =
|
|
78
|
+
(process.env.APP_BRANCH && process.env.APP_BRANCH.trim()) ||
|
|
79
|
+
(process.env.GIT_BRANCH && process.env.GIT_BRANCH.trim()) ||
|
|
80
|
+
execGit('git rev-parse --abbrev-ref HEAD', cwd) ||
|
|
81
|
+
'main';
|
|
82
|
+
|
|
83
|
+
const rawDate =
|
|
84
|
+
(process.env.APP_COMMIT_DATE && process.env.APP_COMMIT_DATE.trim()) ||
|
|
85
|
+
execGit('git log -1 --format=%ci', cwd);
|
|
86
|
+
const commitDate = rawDate ? rawDate.slice(0, 16) : '';
|
|
87
|
+
|
|
88
|
+
const buildTime =
|
|
89
|
+
(process.env.BUILD_TIME && process.env.BUILD_TIME.trim()) ||
|
|
90
|
+
bootTime;
|
|
91
|
+
|
|
92
|
+
cachedBuildInfo = {
|
|
93
|
+
commit,
|
|
94
|
+
branch,
|
|
95
|
+
commitDate,
|
|
96
|
+
buildTime,
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
return cachedBuildInfo;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Resolve local network IPv4 address.
|
|
104
|
+
*/
|
|
105
|
+
export function getNetworkIp() {
|
|
106
|
+
try {
|
|
107
|
+
const interfaces = os.networkInterfaces();
|
|
108
|
+
for (const name of Object.keys(interfaces)) {
|
|
109
|
+
for (const iface of interfaces[name]) {
|
|
110
|
+
if (iface.family === 'IPv4' && !iface.internal) {
|
|
111
|
+
return iface.address;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
} catch {
|
|
116
|
+
// fallback
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Print standardized start-up banner.
|
|
123
|
+
*/
|
|
124
|
+
export function printServerBanner({
|
|
125
|
+
port,
|
|
126
|
+
elapsed,
|
|
127
|
+
commit,
|
|
128
|
+
shouldSyncDb = false,
|
|
129
|
+
isSynced = false,
|
|
130
|
+
networkIp = undefined,
|
|
131
|
+
}) {
|
|
132
|
+
const commitTag = commit ? ' \x1b[32m' + commit + '\x1b[0m' : '';
|
|
133
|
+
const resolvedIp = (networkIp !== undefined && networkIp !== null) ? networkIp : getNetworkIp();
|
|
134
|
+
|
|
135
|
+
console.log('\n \x1b[32m\x1b[1mSERVER\x1b[0m' + commitTag + ' \x1b[90mready in ' + elapsed + ' ms\x1b[0m\n');
|
|
136
|
+
console.log(' \x1b[32m➜\x1b[0m \x1b[1mLocal:\x1b[0m \x1b[36mhttp://localhost:' + port + '/\x1b[0m');
|
|
137
|
+
if (resolvedIp) {
|
|
138
|
+
console.log(' \x1b[32m➜\x1b[0m \x1b[1mNetwork:\x1b[0m \x1b[36mhttp://' + resolvedIp + ':' + port + '/\x1b[0m');
|
|
139
|
+
}
|
|
140
|
+
const dbStatus = isSynced
|
|
141
|
+
? '\x1b[32mSynced\x1b[0m'
|
|
142
|
+
: '\x1b[90mSkipped (pass -s to sync)\x1b[0m';
|
|
143
|
+
console.log(' \x1b[32m➜\x1b[0m \x1b[1mDatabase:\x1b[0m ' + dbStatus + '\n');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Helper to create a router with route metadata.
|
|
148
|
+
*/
|
|
149
|
+
export function createRouter(options = {}) {
|
|
150
|
+
const expressModule = options.express || (typeof require !== 'undefined' ? require('express') : null);
|
|
151
|
+
if (!expressModule) {
|
|
152
|
+
throw new Error('[cynx/server] express is required to use createRouter');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const router = expressModule.Router(options.routerOptions || {});
|
|
156
|
+
if (options.prefix) {
|
|
157
|
+
router._cynxPrefix = options.prefix;
|
|
158
|
+
}
|
|
159
|
+
return router;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Auto-discover and mount routes from a directory.
|
|
164
|
+
*/
|
|
165
|
+
export function loadRoutes(app, routesDir, options = {}) {
|
|
166
|
+
if (!routesDir || !fs.existsSync(routesDir)) {
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const customPrefixes = options.routePrefixes || {};
|
|
171
|
+
const mounted = [];
|
|
172
|
+
const files = fs.readdirSync(routesDir);
|
|
173
|
+
|
|
174
|
+
for (const file of files) {
|
|
175
|
+
const ext = path.extname(file);
|
|
176
|
+
if (!['.js', '.cjs', '.mjs'].includes(ext)) continue;
|
|
177
|
+
if (file.startsWith('.') || file.startsWith('_')) continue;
|
|
178
|
+
|
|
179
|
+
const baseName = path.basename(file, ext);
|
|
180
|
+
const fullPath = path.resolve(routesDir, file);
|
|
181
|
+
|
|
182
|
+
let routeModule;
|
|
183
|
+
try {
|
|
184
|
+
routeModule = typeof require !== 'undefined' ? require(fullPath) : null;
|
|
185
|
+
} catch (err) {
|
|
186
|
+
console.error(`[cynx/server] Error loading route file ${file}:`, err);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (!routeModule) continue;
|
|
191
|
+
|
|
192
|
+
const router = routeModule.default || routeModule.router || routeModule;
|
|
193
|
+
if (typeof router !== 'function' && (!router || typeof router.use !== 'function')) {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Determine mount prefix(es)
|
|
198
|
+
let prefixes = router._cynxPrefix || router.prefix || customPrefixes[baseName];
|
|
199
|
+
if (!prefixes) {
|
|
200
|
+
prefixes = `/api/${baseName}`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const prefixList = Array.isArray(prefixes) ? prefixes : [prefixes];
|
|
204
|
+
for (const prefix of prefixList) {
|
|
205
|
+
app.use(prefix, router);
|
|
206
|
+
mounted.push({ file, prefix });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return mounted;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Create and configure standardized Express application and HTTP server.
|
|
215
|
+
*/
|
|
216
|
+
export function createServer(options = {}) {
|
|
217
|
+
const expressModule = options.express || (typeof require !== 'undefined' ? require('express') : null);
|
|
218
|
+
if (!expressModule) {
|
|
219
|
+
throw new Error('[cynx/server] express is required to create a server');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const app = options.app || expressModule();
|
|
223
|
+
const startTime = Date.now();
|
|
224
|
+
|
|
225
|
+
// 1. CORS
|
|
226
|
+
if (options.cors !== false) {
|
|
227
|
+
const corsModule = options.corsMiddleware || (typeof require !== 'undefined' ? require('cors') : null);
|
|
228
|
+
if (corsModule) {
|
|
229
|
+
app.use(typeof options.cors === 'object' ? corsModule(options.cors) : corsModule());
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 2. Compression
|
|
234
|
+
if (options.compression) {
|
|
235
|
+
if (typeof options.compression === 'function') {
|
|
236
|
+
app.use(options.compression);
|
|
237
|
+
} else {
|
|
238
|
+
const compModule = typeof require !== 'undefined' ? require('compression') : null;
|
|
239
|
+
if (compModule) app.use(compModule());
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// 3. Body Parsers
|
|
244
|
+
const limit = options.bodyLimit || '5mb';
|
|
245
|
+
app.use(expressModule.json({ limit }));
|
|
246
|
+
app.use(expressModule.urlencoded({ extended: true, limit }));
|
|
247
|
+
|
|
248
|
+
// 4. Hook before routes (custom loggers, metrics, etc.)
|
|
249
|
+
if (typeof options.beforeRoutes === 'function') {
|
|
250
|
+
options.beforeRoutes(app);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 5. Auto-mount routes
|
|
254
|
+
if (options.routesDir) {
|
|
255
|
+
loadRoutes(app, options.routesDir, options);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// 6. Explicit routes list
|
|
259
|
+
if (Array.isArray(options.routes)) {
|
|
260
|
+
for (const route of options.routes) {
|
|
261
|
+
if (route.prefix && route.router) {
|
|
262
|
+
const list = Array.isArray(route.prefix) ? route.prefix : [route.prefix];
|
|
263
|
+
for (const p of list) {
|
|
264
|
+
app.use(p, route.router);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// 7. Built-in healthcheck
|
|
271
|
+
if (options.healthcheck !== false) {
|
|
272
|
+
app.get('/api/health', (_req, res) => res.json({ status: 'ok' }));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// 8. Hook before error handler (e.g. Sentry.setupExpressErrorHandler)
|
|
276
|
+
if (typeof options.beforeErrorHandler === 'function') {
|
|
277
|
+
options.beforeErrorHandler(app);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// 9. Standardized JSON Error Handler
|
|
281
|
+
if (options.errorHandler !== false) {
|
|
282
|
+
app.use((err, _req, res, _next) => {
|
|
283
|
+
console.error('[HTTP]', err);
|
|
284
|
+
res.status(err.status || 500).json({ error: err.message || 'Internal server error' });
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// 10. Process level unhandled error safety
|
|
289
|
+
if (options.processHandlers !== false) {
|
|
290
|
+
process.on('unhandledRejection', (reason) => {
|
|
291
|
+
console.error('[System]', reason);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
process.on('uncaughtException', (err) => {
|
|
295
|
+
console.error('[System]', err);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const port = options.port || process.env.BACKEND_PORT || process.env.PORT || 3000;
|
|
300
|
+
const host = options.host || '0.0.0.0';
|
|
301
|
+
let httpServer = null;
|
|
302
|
+
|
|
303
|
+
return {
|
|
304
|
+
app,
|
|
305
|
+
get httpServer() {
|
|
306
|
+
return httpServer;
|
|
307
|
+
},
|
|
308
|
+
port,
|
|
309
|
+
host,
|
|
310
|
+
start: function (onReady) {
|
|
311
|
+
return new Promise((resolve, reject) => {
|
|
312
|
+
try {
|
|
313
|
+
httpServer = app.listen(port, host, async () => {
|
|
314
|
+
const elapsed = Date.now() - startTime;
|
|
315
|
+
const build = app_build_info();
|
|
316
|
+
|
|
317
|
+
// Print banner if not disabled
|
|
318
|
+
if (options.banner !== false) {
|
|
319
|
+
printServerBanner({
|
|
320
|
+
port,
|
|
321
|
+
elapsed,
|
|
322
|
+
commit: build.commit,
|
|
323
|
+
shouldSyncDb: options.shouldSyncDb,
|
|
324
|
+
isSynced: options.isSynced,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (typeof options.onStart === 'function') {
|
|
329
|
+
try {
|
|
330
|
+
await options.onStart({ app, httpServer, port, host, elapsed, build });
|
|
331
|
+
} catch (onStartErr) {
|
|
332
|
+
console.error('[cynx/server] onStart error:', onStartErr);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (typeof onReady === 'function') {
|
|
337
|
+
onReady({ app, httpServer, port, host, elapsed, build });
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
resolve({ app, httpServer, port, host, elapsed, build });
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
httpServer.keepAliveTimeout = options.keepAliveTimeout || 65000;
|
|
344
|
+
httpServer.headersTimeout = options.headersTimeout || 66000;
|
|
345
|
+
} catch (listenErr) {
|
|
346
|
+
reject(listenErr);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
},
|
|
350
|
+
stop: function () {
|
|
351
|
+
return new Promise((resolve) => {
|
|
352
|
+
if (httpServer) {
|
|
353
|
+
httpServer.close(() => resolve());
|
|
354
|
+
} else {
|
|
355
|
+
resolve();
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export default {
|
|
363
|
+
createServer,
|
|
364
|
+
createRouter,
|
|
365
|
+
loadRoutes,
|
|
366
|
+
app_commit,
|
|
367
|
+
app_build_info,
|
|
368
|
+
printServerBanner,
|
|
369
|
+
getNetworkIp,
|
|
370
|
+
execGit,
|
|
371
|
+
};
|