data-primals-engine 1.2.6-rc1 → 1.2.6-rc3

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 CHANGED
@@ -315,7 +315,7 @@ curl -X DELETE http://localhost:7633/api/data?_user=demo \
315
315
  Make sure you use the code below to initialize the user :
316
316
  ```javascript
317
317
  import express from "express";
318
- import {Engine, insertData, searchData } from './src/index';
318
+ import {Engine, insertData, searchData } from 'data-primals-engine';
319
319
 
320
320
  // Ensure the engine is initialized
321
321
 
package/package.json CHANGED
@@ -1,120 +1,120 @@
1
- {
2
- "name": "data-primals-engine",
3
- "version": "1.2.6-rc1",
4
- "description": "data-primals-engine is a package responsible from handling large amount of data using MongoDB in a practical and performant way. It can also get workflow models working (for automation), and fully supports internationalisation. It also has integrated AI assistant.",
5
- "main": "src/engine.js",
6
- "type": "module",
7
- "scripts": {
8
- "preinstall": "npx force-resolutions",
9
- "dev": "concurrently \"npm:client\" \"npm:devserver\"",
10
- "prod": "npm run build-server && npm run server",
11
- "client": "cd client && npm run dev",
12
- "build-server": "vite build client --config client/vite.config.js --outDir dist",
13
- "build-client": "cd client && npm run build",
14
- "server": "cross-env NODE_ENV=production node server.js",
15
- "devserver": "npm run build-server && cross-env NODE_ENV=development PORT=7633 node server.js",
16
- "lint": "eslint .",
17
- "format": "prettier --write .",
18
- "clean": "rm -rf node_modules package-lock.json",
19
- "test": "cross-env MONGO_DB_URL=\"mongodb://localhost:27017\" PORT=7635 vitest --no-file-parallelism",
20
- "audit": "npm audit --audit-level=high",
21
- "migrate:create": "node src/migrate.js create",
22
- "migrate:up": "node src/migrate.js up",
23
- "migrate:down": "node src/migrate.js down",
24
- "migrate:revert": "node src/migrate.js revert",
25
- "migrate:status": "node src/migrate.js status"
26
- },
27
- "optionalDependencies": {
28
- "@rollup/rollup-linux-x64-gnu": "4.6.1"
29
- },
30
- "resolutions": {
31
- "tar-fs": "3.0.9",
32
- "on-headers": "1.1.0",
33
- "brace-expansion": "2.0.2",
34
- "prismjs": "1.30.0"
35
- },
36
- "repository": {
37
- "type": "git",
38
- "url": "https://github.com/anonympins/data-primals-engine.git"
39
- },
40
- "exports": {
41
- ".": "./src/index.js",
42
- "./modules/*.js": "./src/modules/*.js",
43
- "./modules/*": "./src/modules/*/index.js",
44
- "./client": "./client/index.js",
45
- "./*": "./src/*.js"
46
- },
47
- "peerDependencies": {
48
- "express": "^5.1.0",
49
- "react": ">=18.0.0",
50
- "react-query": ">=3.0.0"
51
- },
52
- "dependencies": {
53
- "@langchain/core": "^0.3.66",
54
- "@langchain/deepseek": "^0.1.0",
55
- "@langchain/google-genai": "^0.2.16",
56
- "@langchain/openai": "^0.6.3",
57
- "archiver": "^7.0.1",
58
- "aws-sdk": "^2.1692.0",
59
- "bcrypt": "^6.0.0",
60
- "body-parser": "^2.2.0",
61
- "chalk": "^5.4.1",
62
- "check-disk-space": "^3.4.0",
63
- "compression": "^1.8.1",
64
- "cookie-parser": "^1.4.7",
65
- "cronstrue": "^3.2.0",
66
- "csv-parse": "^6.1.0",
67
- "date-fns": "^4.1.0",
68
- "express-csrf-double-submit-cookie": "^2.0.0",
69
- "express-formidable": "^1.2.0",
70
- "express-mongo-sanitize": "^2.2.0",
71
- "express-rate-limit": "^8.0.1",
72
- "express-session": "^1.18.2",
73
- "i18next-browser-languagedetector": "^8.2.0",
74
- "isolated-vm": "^4.7.2",
75
- "juice": "^11.0.1",
76
- "mathjs": "^14.6.0",
77
- "mongodb": "^6.18.0",
78
- "node-cache": "^5.1.2",
79
- "node-schedule": "^2.1.1",
80
- "nodemailer": "^7.0.5",
81
- "openai": "^5.10.2",
82
- "process": "^0.11.10",
83
- "prop-types": "^15.8.1",
84
- "randomcolor": "^0.6.2",
85
- "react-i18next": "^15.6.1",
86
- "react-markdown": "^10.1.0",
87
- "read-excel-file": "^5.8.8",
88
- "request-ip": "^3.3.0",
89
- "sanitize-html": "^2.17.0",
90
- "sirv": "^3.0.1",
91
- "swagger-ui-express": "^5.0.1",
92
- "tar": "^7.4.3",
93
- "uniqid": "^5.4.0",
94
- "vitest": "^3.2.4",
95
- "yaml": "^2.8.0"
96
- },
97
- "devDependencies": {
98
- "@eslint/js": "^9.32.0",
99
- "concurrently": "^9.2.0",
100
- "cross-env": "^10.0.0",
101
- "eslint": "^9.32.0",
102
- "globals": "^16.3.0"
103
- },
104
- "subPackages": [
105
- "client"
106
- ],
107
- "keywords": [
108
- "data-driven engine",
109
- "headless CMS",
110
- "backend",
111
- "automation",
112
- "AWS S3",
113
- "MongoDB"
114
- ],
115
- "author": "anonympins",
116
- "license": "MIT",
117
- "engines": {
118
- "node": ">=20.0.0"
119
- }
120
- }
1
+ {
2
+ "name": "data-primals-engine",
3
+ "version": "1.2.6-rc3",
4
+ "description": "data-primals-engine is a package responsible from handling large amount of data using MongoDB in a practical and performant way. It can also get workflow models working (for automation), and fully supports internationalisation. It also has integrated AI assistant.",
5
+ "main": "src/engine.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "preinstall": "npx force-resolutions",
9
+ "dev": "concurrently \"npm:client\" \"npm:devserver\"",
10
+ "prod": "npm run build-server && npm run server",
11
+ "client": "cd client && npm run dev",
12
+ "build-server": "vite build client --config client/vite.config.js --outDir dist",
13
+ "build-client": "cd client && npm run build",
14
+ "server": "cross-env NODE_ENV=production node server.js",
15
+ "devserver": "npm run build-server && cross-env NODE_ENV=development PORT=7633 node server.js",
16
+ "lint": "eslint .",
17
+ "format": "prettier --write .",
18
+ "clean": "rm -rf node_modules package-lock.json",
19
+ "test": "cross-env MONGO_DB_URL=\"mongodb://localhost:27017\" PORT=7635 vitest --no-file-parallelism",
20
+ "audit": "npm audit --audit-level=high",
21
+ "migrate:create": "node src/migrate.js create",
22
+ "migrate:up": "node src/migrate.js up",
23
+ "migrate:down": "node src/migrate.js down",
24
+ "migrate:revert": "node src/migrate.js revert",
25
+ "migrate:status": "node src/migrate.js status"
26
+ },
27
+ "optionalDependencies": {
28
+ "@rollup/rollup-linux-x64-gnu": "4.6.1"
29
+ },
30
+ "resolutions": {
31
+ "tar-fs": "3.0.9",
32
+ "on-headers": "1.1.0",
33
+ "brace-expansion": "2.0.2",
34
+ "prismjs": "1.30.0"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/anonympins/data-primals-engine.git"
39
+ },
40
+ "exports": {
41
+ ".": "./src/index.js",
42
+ "./modules/*.js": "./src/modules/*.js",
43
+ "./modules/*": "./src/modules/*/index.js",
44
+ "./client": "./client/index.js",
45
+ "./*": "./src/*.js"
46
+ },
47
+ "peerDependencies": {
48
+ "express": "^5.1.0",
49
+ "react": ">=18.0.0",
50
+ "react-query": ">=3.0.0"
51
+ },
52
+ "dependencies": {
53
+ "@langchain/core": "^0.3.66",
54
+ "@langchain/deepseek": "^0.1.0",
55
+ "@langchain/google-genai": "^0.2.16",
56
+ "@langchain/openai": "^0.6.3",
57
+ "archiver": "^7.0.1",
58
+ "aws-sdk": "^2.1692.0",
59
+ "bcrypt": "^6.0.0",
60
+ "body-parser": "^2.2.0",
61
+ "chalk": "^5.4.1",
62
+ "check-disk-space": "^3.4.0",
63
+ "compression": "^1.8.1",
64
+ "cookie-parser": "^1.4.7",
65
+ "cronstrue": "^3.2.0",
66
+ "csv-parse": "^6.1.0",
67
+ "date-fns": "^4.1.0",
68
+ "express-csrf-double-submit-cookie": "^2.0.0",
69
+ "express-formidable": "^1.2.0",
70
+ "express-mongo-sanitize": "^2.2.0",
71
+ "express-rate-limit": "^8.0.1",
72
+ "express-session": "^1.18.2",
73
+ "i18next-browser-languagedetector": "^8.2.0",
74
+ "isolated-vm": "^4.7.2",
75
+ "juice": "^11.0.1",
76
+ "mathjs": "^14.6.0",
77
+ "mongodb": "^6.18.0",
78
+ "node-cache": "^5.1.2",
79
+ "node-schedule": "^2.1.1",
80
+ "nodemailer": "^7.0.5",
81
+ "openai": "^5.10.2",
82
+ "process": "^0.11.10",
83
+ "prop-types": "^15.8.1",
84
+ "randomcolor": "^0.6.2",
85
+ "react-i18next": "^15.6.1",
86
+ "react-markdown": "^10.1.0",
87
+ "read-excel-file": "^5.8.8",
88
+ "request-ip": "^3.3.0",
89
+ "sanitize-html": "^2.17.0",
90
+ "sirv": "^3.0.1",
91
+ "swagger-ui-express": "^5.0.1",
92
+ "tar": "^7.4.3",
93
+ "uniqid": "^5.4.0",
94
+ "vitest": "^3.2.4",
95
+ "yaml": "^2.8.0"
96
+ },
97
+ "devDependencies": {
98
+ "@eslint/js": "^9.32.0",
99
+ "concurrently": "^9.2.0",
100
+ "cross-env": "^10.0.0",
101
+ "eslint": "^9.32.0",
102
+ "globals": "^16.3.0"
103
+ },
104
+ "subPackages": [
105
+ "client"
106
+ ],
107
+ "keywords": [
108
+ "data-driven engine",
109
+ "headless CMS",
110
+ "backend",
111
+ "automation",
112
+ "AWS S3",
113
+ "MongoDB"
114
+ ],
115
+ "author": "anonympins",
116
+ "license": "MIT",
117
+ "engines": {
118
+ "node": ">=20.0.0"
119
+ }
120
+ }
package/server.js CHANGED
@@ -8,7 +8,7 @@ import {Config, Engine, BenchmarkTool, GameObject, Logger} from "./src/index.js"
8
8
  import sirv from "sirv";
9
9
  import express from "express";
10
10
 
11
- Config.Set("modules", ["data", "mongodb", "file", "bucket", "workflow","user", "assistant", "swagger"])
11
+ Config.Set("modules", ["mongodb", "data", "file", "bucket", "workflow","user", "assistant", "swagger"])
12
12
  Config.Set("middlewares", []);
13
13
 
14
14
  const bench = GameObject.Create("Benchmark");
package/src/engine.js CHANGED
@@ -1,281 +1,285 @@
1
- import {GameObject, Logger} from "./gameObject.js";
2
- import {Config} from "./config.js";
3
- import fs from 'node:fs'
4
- import express from 'express'
5
- import {MongoClient as InternalMongoClient} from 'mongodb'
6
- import process from "process";
7
- import {
8
- cookiesSecret,
9
- databasePoolSize,
10
- dbName,
11
- tlsAllowInvalidCertificates, tlsAllowInvalidHostnames
12
- } from "./constants.js";
13
- import http from "http";
14
- import cookieParser from "cookie-parser";
15
- import requestIp from 'request-ip';
16
- import {createModel, deleteModels, getModels, installAllPacks, validateModelStructure} from "./modules/data/data.js";
17
- import {defaultModels} from "./defaultModels.js";
18
- import {DefaultUserProvider} from "./providers.js";
19
- import formidableMiddleware from 'express-formidable';
20
- import sirv from "sirv";
21
- import * as tls from "node:tls";
22
- import {Event} from "./events.js";
23
- import path from "node:path";
24
- import {isPathRelativeTo, isValidPath} from "./core.js";
25
-
26
- // Constants
27
- const isProduction = process.env.NODE_ENV === 'production'
28
-
29
- let caFile, certFile, keyFile;
30
- try {
31
- if (process.env.CA_CERT)
32
- caFile = fs.readFileSync(process.env.CA_CERT);
33
- } catch (e) {}
34
- try {
35
- if (process.env.CERT)
36
- certFile = fs.readFileSync(process.env.CERT);
37
- }catch (e) {}
38
- try{
39
- if (process.env.CERT_KEY)
40
- keyFile = fs.readFileSync(process.env.CERT_KEY);
41
- } catch (e) {}
42
-
43
- const secureContext = tls.createSecureContext({
44
- ca: caFile, cert: certFile, key: keyFile
45
- });
46
-
47
- export const dbUrl = process.env.CI ? 'mongodb://mongodb:27017' : (process.env.MONGO_DB_URL || 'mongodb://127.0.0.1:27017');
48
-
49
- const isTlsActive = !(!process.env.TLS || ["0", "false"].includes(process.env.TLS.toLowerCase()));
50
-
51
- const clientOptions = {
52
- maxPoolSize: databasePoolSize
53
- };
54
-
55
- // We add TLS options if enabled
56
- if (isTlsActive) {
57
- clientOptions.tls = true;
58
-
59
- // is mTLS ? (client certificate required instead of password)
60
- if (process.env.CERT) {
61
- clientOptions.secureContext = tls.createSecureContext({
62
- ca: fs.readFileSync(process.env.CA_CERT),
63
- cert: fs.readFileSync(process.env.CERT),
64
- key: fs.readFileSync(process.env.CERT_KEY)
65
- });
66
- }else {
67
- // Path to the authority certificate
68
- if (process.env.CA_CERT) {
69
- clientOptions.tlsCAFile = process.env.CA_CERT;
70
- }
71
- // Path to the certificate key
72
- if (process.env.CERT_KEY) {
73
- clientOptions.tlsCertificateKeyFile = process.env.CERT_KEY;
74
- }
75
- }
76
- if (tlsAllowInvalidCertificates) {
77
- clientOptions.tlsAllowInvalidCertificates = true;
78
- console.warn("🚨 [SECURITY WARNING] tlsAllowInvalidCertificates is ON. Server certificate will not be validated.");
79
- }
80
- if (tlsAllowInvalidHostnames) {
81
- clientOptions.tlsAllowInvalidHostnames = true;
82
- console.warn("🚨 [SECURITY WARNING] tlsAllowInvalidHostnames is ON. Server hostname will not be validated.");
83
- }
84
- }
85
-
86
- export const MongoClient = new InternalMongoClient(dbUrl, clientOptions);
87
-
88
-
89
- // Database Name
90
- export const MongoDatabase = MongoClient.db(dbName);
91
-
92
-
93
- export const Engine = {
94
- Create: async (options = { app : null}) => {
95
- const engine = GameObject.Create("Engine");
96
- console.log("Creating engine", Config.Get('modules'));
97
- const logger = engine.addComponent(Logger);
98
-
99
- engine.userProvider = new DefaultUserProvider(engine);
100
-
101
- engine.setUserProvider = (providerInstance) => {
102
- engine.userProvider = providerInstance;
103
- logger.info(`Custom UserProvider '${providerInstance.constructor.name}' has been set.`);
104
- };
105
-
106
- if (!options.app) {
107
- options.app = express();
108
- }
109
-
110
- const { app } = options;
111
- // Allows you to set port in the project properties.
112
- app.set('port', process.env.PORT || 3000);
113
- app.set('engine', engine);
114
-
115
- app.use(formidableMiddleware({
116
- encoding: 'utf-8',
117
- uploadDir: process.cwd()+'/uploads/tmp',
118
- multiples: true // req.files to be arrays of files
119
- }));
120
- app.use(cookieParser(process.env.COOKIES_SECRET || cookiesSecret));
121
- app.use(requestIp.mw())
122
-
123
- engine.use = (...args) => {
124
- return app.use(...args);
125
- }
126
- engine.post = (...args) => {
127
- return app.post(...args);
128
- };
129
- engine.get = (...args) => {
130
- return app.get(...args);
131
- };
132
- engine.delete = (...args) => {
133
- return app.delete(...args);
134
- };
135
- engine.patch = (...args) => {
136
- return app.patch(...args);
137
- };
138
- engine.put = (...args) => {
139
- return app.put(...args);
140
- };
141
- engine.all = (...args) => {
142
- return app.all(...args);
143
- };
144
- engine.getModule = (module) => {
145
- return engine._modules.find(m => m.module === module);
146
- };
147
-
148
- const importModule = async (module) => {
149
- const moduleA = await import(module);
150
- if (moduleA.onInit){
151
- await moduleA.onInit(engine);
152
- return {...moduleA, module};
153
- }else {
154
- const mod = moduleA.default();
155
- await mod?.onInit(engine);
156
- return { ...mod, module};
157
- }
158
- };
159
-
160
- await Promise.all(Config.Get('modules', []).map(async moduleIdentifier => {
161
- try {
162
- let moduleDir;
163
- const moduleName = path.basename(moduleIdentifier);
164
-
165
- const directPath = path.resolve(moduleIdentifier);
166
- let isDir = fs.existsSync(directPath) && fs.statSync(directPath).isDirectory();
167
- if (isDir) {
168
- moduleDir = directPath;
169
- if (!fs.existsSync(moduleDir) || !fs.statSync(moduleDir).isDirectory()) {
170
- logger.warn(`Le dossier du module est introuvable pour l'identifiant : '${moduleIdentifier}'. Chemin cherché : '${moduleDir}'.`);
171
- return null;
172
- }
173
- } else {
174
- moduleDir = path.resolve('./src/modules', moduleIdentifier);
175
- }
176
-
177
- let moduleEntryPoint;
178
- const jsPath = moduleDir+'.js';
179
- const indexJsPath = path.join(moduleDir, 'index.js');
180
- const moduleJsPath = path.join(moduleDir, `${moduleName}.js`);
181
-
182
- if (fs.existsSync(jsPath)) {
183
- moduleEntryPoint = 'file://'+jsPath;
184
- } else if (fs.existsSync(indexJsPath)) {
185
- moduleEntryPoint = 'file://'+indexJsPath;
186
- } else if (fs.existsSync(moduleJsPath)) {
187
- moduleEntryPoint = 'file://'+moduleJsPath;
188
- }
189
-
190
- return await importModule(moduleEntryPoint);
191
- } catch (e) {
192
- logger.error(`Échec du chargement du module '${moduleIdentifier}':`, e.stack);
193
- return null;
194
- }
195
- })).then(async results => {
196
- // On filtre les modules qui n'ont pas pu être chargés
197
- engine._modules = results.filter(Boolean);
198
- return Promise.resolve();
199
- });
200
-
201
- let server;
202
-
203
- engine.start = async (port, cb) =>{
204
- // Use connect method to connect to the server
205
-
206
- // Start http server
207
- server = http.createServer(app);
208
-
209
- // Server Timeout Settings
210
- server.timeout = 120000;
211
- server.headersTimeout = 20000;
212
- server.requestTimeout = 30000;
213
- server.keepAliveTimeout = 5000;
214
-
215
- server.listen(port);
216
-
217
- await setupInitialModels();
218
- await installAllPacks();
219
-
220
- if (cb)
221
- await cb();
222
-
223
- engine.get('/api/health', (req, res) => {
224
- res.status(200).json({
225
- status: 'ok',
226
- timestamp: new Date().toISOString()
227
- });
228
- });
229
-
230
- app.use(sirv('client/dist', {
231
- single: true,
232
- dev: process.env.NODE_ENV === 'development'
233
- }));
234
-
235
- process.on('uncaughtException', function (exception) {
236
- console.error(exception);
237
- fs.appendFile('issues.txt', JSON.stringify({ code: exception.code, message: exception.message, stack: exception.stack }), function (err) {
238
- if (err){
239
- throw err;
240
- }
241
- });
242
- process.exit(1);
243
- });
244
-
245
- Event.Trigger("OnServerStart", "event", "system", engine);
246
- }
247
-
248
- engine.stop = async () => {
249
- await server.close();
250
- Event.Trigger("OnServerStop", "event", "system", engine);
251
- };
252
-
253
- async function setupInitialModels() {
254
- logger.info("Validating structures of default models...");
255
- const ms = Object.values(Config.Get('defaultModels', defaultModels));
256
-
257
- let dbModels = await getModels();
258
-
259
- for(let i = 0; i < ms.length; ++i){
260
- const model = ms[i];
261
- validateModelStructure(model);
262
- // Création des modèles
263
- if( !dbModels.find(m =>m.name === model.name) )
264
- {
265
- model.locked = true;
266
- const r = await createModel(model);
267
- dbModels.push({...model, _id: r.insertedId });
268
- logger.info('Model inserted (' + model.name + ')');
269
- }else
270
- logger.info('Model loaded (' + model.name + ')');
271
- }
272
- logger.info("All models loaded.");
273
- Event.Trigger("OnModelsLoaded", "event", "system", engine, dbModels);
274
- }
275
- engine.resetModels = async () => {
276
- await deleteModels();
277
- Event.Trigger("OnModelsDeleted", "event", "system", engine);
278
- };
279
- return engine;
280
- }
281
- }
1
+ import {GameObject, Logger} from "./gameObject.js";
2
+ import {Config} from "./config.js";
3
+ import fs from 'node:fs'
4
+ import express from 'express'
5
+ import {MongoClient as InternalMongoClient} from 'mongodb'
6
+ import process from "process";
7
+ import {
8
+ cookiesSecret,
9
+ databasePoolSize,
10
+ dbName,
11
+ tlsAllowInvalidCertificates, tlsAllowInvalidHostnames
12
+ } from "./constants.js";
13
+ import http from "http";
14
+ import cookieParser from "cookie-parser";
15
+ import requestIp from 'request-ip';
16
+ import {createModel, deleteModels, getModels, installAllPacks, validateModelStructure} from "./modules/data/data.js";
17
+ import {defaultModels} from "./defaultModels.js";
18
+ import {DefaultUserProvider} from "./providers.js";
19
+ import formidableMiddleware from 'express-formidable';
20
+ import sirv from "sirv";
21
+ import * as tls from "node:tls";
22
+ import {Event} from "./events.js";
23
+ import path from "node:path";
24
+ import { fileURLToPath } from 'node:url';
25
+ // Constants
26
+
27
+ // On définit __dirname pour obtenir le chemin absolu du répertoire courant,
28
+ // ce qui est la méthode standard en ES Modules.
29
+ const __filename = fileURLToPath(import.meta.url);
30
+ const __dirname = path.dirname(__filename);
31
+
32
+
33
+ let caFile, certFile, keyFile;
34
+ try {
35
+ if (process.env.CA_CERT)
36
+ caFile = fs.readFileSync(process.env.CA_CERT);
37
+ } catch (e) {}
38
+ try {
39
+ if (process.env.CERT)
40
+ certFile = fs.readFileSync(process.env.CERT);
41
+ }catch (e) {}
42
+ try{
43
+ if (process.env.CERT_KEY)
44
+ keyFile = fs.readFileSync(process.env.CERT_KEY);
45
+ } catch (e) {}
46
+
47
+ const secureContext = tls.createSecureContext({
48
+ ca: caFile, cert: certFile, key: keyFile
49
+ });
50
+
51
+ export const dbUrl = process.env.CI ? 'mongodb://mongodb:27017' : (process.env.MONGO_DB_URL || 'mongodb://127.0.0.1:27017');
52
+
53
+ const isTlsActive = !(!process.env.TLS || ["0", "false"].includes(process.env.TLS.toLowerCase()));
54
+
55
+ const clientOptions = {
56
+ maxPoolSize: databasePoolSize
57
+ };
58
+
59
+ // We add TLS options if enabled
60
+ if (isTlsActive) {
61
+ clientOptions.tls = true;
62
+
63
+ // is mTLS ? (client certificate required instead of password)
64
+ if (process.env.CERT) {
65
+ clientOptions.secureContext = tls.createSecureContext({
66
+ ca: fs.readFileSync(process.env.CA_CERT),
67
+ cert: fs.readFileSync(process.env.CERT),
68
+ key: fs.readFileSync(process.env.CERT_KEY)
69
+ });
70
+ }else {
71
+ // Path to the authority certificate
72
+ if (process.env.CA_CERT) {
73
+ clientOptions.tlsCAFile = process.env.CA_CERT;
74
+ }
75
+ // Path to the certificate key
76
+ if (process.env.CERT_KEY) {
77
+ clientOptions.tlsCertificateKeyFile = process.env.CERT_KEY;
78
+ }
79
+ }
80
+ if (tlsAllowInvalidCertificates) {
81
+ clientOptions.tlsAllowInvalidCertificates = true;
82
+ console.warn("🚨 [SECURITY WARNING] tlsAllowInvalidCertificates is ON. Server certificate will not be validated.");
83
+ }
84
+ if (tlsAllowInvalidHostnames) {
85
+ clientOptions.tlsAllowInvalidHostnames = true;
86
+ console.warn("🚨 [SECURITY WARNING] tlsAllowInvalidHostnames is ON. Server hostname will not be validated.");
87
+ }
88
+ }
89
+
90
+ export const MongoClient = new InternalMongoClient(dbUrl, clientOptions);
91
+
92
+
93
+ // Database Name
94
+ export const MongoDatabase = MongoClient.db(dbName);
95
+
96
+
97
+ export const Engine = {
98
+ Create: async (options = { app : null}) => {
99
+ const engine = GameObject.Create("Engine");
100
+ console.log("Creating engine", Config.Get('modules'));
101
+ const logger = engine.addComponent(Logger);
102
+
103
+ engine.userProvider = new DefaultUserProvider(engine);
104
+
105
+ engine.setUserProvider = (providerInstance) => {
106
+ engine.userProvider = providerInstance;
107
+ logger.info(`Custom UserProvider '${providerInstance.constructor.name}' has been set.`);
108
+ };
109
+
110
+ if (!options.app) {
111
+ options.app = express();
112
+ }
113
+
114
+ const { app } = options;
115
+ // Allows you to set port in the project properties.
116
+ app.set('port', process.env.PORT || 3000);
117
+ app.set('engine', engine);
118
+
119
+ app.use(formidableMiddleware({
120
+ encoding: 'utf-8',
121
+ uploadDir: process.cwd()+'/uploads/tmp',
122
+ multiples: true // req.files to be arrays of files
123
+ }));
124
+ app.use(cookieParser(process.env.COOKIES_SECRET || cookiesSecret));
125
+ app.use(requestIp.mw())
126
+
127
+ engine.use = (...args) => {
128
+ return app.use(...args);
129
+ }
130
+ engine.post = (...args) => {
131
+ return app.post(...args);
132
+ };
133
+ engine.get = (...args) => {
134
+ return app.get(...args);
135
+ };
136
+ engine.delete = (...args) => {
137
+ return app.delete(...args);
138
+ };
139
+ engine.patch = (...args) => {
140
+ return app.patch(...args);
141
+ };
142
+ engine.put = (...args) => {
143
+ return app.put(...args);
144
+ };
145
+ engine.all = (...args) => {
146
+ return app.all(...args);
147
+ };
148
+ engine.getModule = (module) => {
149
+ return engine._modules.find(m => m.module === module);
150
+ };
151
+
152
+ const importModule = async (module) => {
153
+ const moduleA = await import(module);
154
+ if (moduleA.onInit){
155
+ await moduleA.onInit(engine);
156
+ return {...moduleA, module};
157
+ }else {
158
+ const mod = moduleA.default();
159
+ await mod?.onInit(engine);
160
+ return { ...mod, module};
161
+ }
162
+ };
163
+
164
+ engine._modules = [];
165
+ for (const moduleIdentifier of Config.Get('modules', [])) {
166
+ try {
167
+ let moduleDir;
168
+ const moduleName = path.basename(moduleIdentifier);
169
+
170
+ const directPath = path.resolve(moduleIdentifier);
171
+ let isDir = fs.existsSync(directPath) && fs.statSync(directPath).isDirectory();
172
+
173
+ if (isDir) {
174
+ moduleDir = directPath;
175
+ } else {
176
+ moduleDir = path.resolve(__dirname, 'modules', moduleIdentifier);
177
+ }
178
+
179
+ let moduleEntryPoint;
180
+ const jsPath = moduleDir + '.js';
181
+ const indexJsPath = path.join(moduleDir, 'index.js');
182
+ const moduleJsPath = path.join(moduleDir, `${moduleName}.js`);
183
+
184
+ if (fs.existsSync(jsPath)) {
185
+ moduleEntryPoint = 'file://' + jsPath;
186
+ } else if (fs.existsSync(indexJsPath)) {
187
+ moduleEntryPoint = 'file://' + indexJsPath;
188
+ } else if (fs.existsSync(moduleJsPath)) {
189
+ moduleEntryPoint = 'file://' + moduleJsPath;
190
+ }
191
+
192
+ if (moduleEntryPoint) {
193
+ const loadedModule = await importModule(moduleEntryPoint);
194
+ if (loadedModule) {
195
+ engine._modules.push(loadedModule);
196
+ }
197
+ } else {
198
+ logger.warn(`Aucun point d'entrée trouvé pour le module '${moduleIdentifier}'.`);
199
+ }
200
+ } catch (e) {
201
+ logger.error(`Échec du chargement du module '${moduleIdentifier}':`, e.stack);
202
+ }
203
+ }
204
+
205
+ let server;
206
+
207
+ engine.start = async (port, cb) =>{
208
+ // Use connect method to connect to the server
209
+
210
+ // Start http server
211
+ server = http.createServer(app);
212
+
213
+ // Server Timeout Settings
214
+ server.timeout = 120000;
215
+ server.headersTimeout = 20000;
216
+ server.requestTimeout = 30000;
217
+ server.keepAliveTimeout = 5000;
218
+
219
+ server.listen(port);
220
+
221
+ await setupInitialModels();
222
+ await installAllPacks();
223
+
224
+ if (cb)
225
+ await cb();
226
+
227
+ engine.get('/api/health', (req, res) => {
228
+ res.status(200).json({
229
+ status: 'ok',
230
+ timestamp: new Date().toISOString()
231
+ });
232
+ });
233
+
234
+ app.use(sirv('client/dist', {
235
+ single: true,
236
+ dev: process.env.NODE_ENV === 'development'
237
+ }));
238
+
239
+ process.on('uncaughtException', function (exception) {
240
+ console.error(exception);
241
+ fs.appendFile('issues.txt', JSON.stringify({ code: exception.code, message: exception.message, stack: exception.stack }), function (err) {
242
+ if (err){
243
+ throw err;
244
+ }
245
+ });
246
+ process.exit(1);
247
+ });
248
+
249
+ Event.Trigger("OnServerStart", "event", "system", engine);
250
+ }
251
+
252
+ engine.stop = async () => {
253
+ await server.close();
254
+ Event.Trigger("OnServerStop", "event", "system", engine);
255
+ };
256
+
257
+ async function setupInitialModels() {
258
+ logger.info("Validating structures of default models...");
259
+ const ms = Object.values(Config.Get('defaultModels', defaultModels));
260
+
261
+ let dbModels = await getModels();
262
+
263
+ for(let i = 0; i < ms.length; ++i){
264
+ const model = ms[i];
265
+ validateModelStructure(model);
266
+ // Création des modèles
267
+ if( !dbModels.find(m =>m.name === model.name) )
268
+ {
269
+ model.locked = true;
270
+ const r = await createModel(model);
271
+ dbModels.push({...model, _id: r.insertedId });
272
+ logger.info('Model inserted (' + model.name + ')');
273
+ }else
274
+ logger.info('Model loaded (' + model.name + ')');
275
+ }
276
+ logger.info("All models loaded.");
277
+ Event.Trigger("OnModelsLoaded", "event", "system", engine, dbModels);
278
+ }
279
+ engine.resetModels = async () => {
280
+ await deleteModels();
281
+ Event.Trigger("OnModelsDeleted", "event", "system", engine);
282
+ };
283
+ return engine;
284
+ }
285
+ }
@@ -1,4 +1,7 @@
1
1
  import NodeCache from "node-cache";
2
+ import i18n from "../../i18n.js";
3
+ import {allowedFields, maxStringLength} from "../../constants.js";
4
+ import path from "node:path";
2
5
 
3
6
  export const modelsCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );
4
7
 
@@ -15,3 +18,73 @@ export const mongoDBWhitelist = [
15
18
  ];
16
19
  export let importJobs = {};
17
20
 
21
+
22
+ /**
23
+ * Exécute une tâche d'import/export (parsing, stringify) dans un worker thread.
24
+ * @param {('parse-json'|'parse-csv'|'stringify-json')} action - L'action à effectuer.
25
+ * @param {object} payload - Les données nécessaires pour l'action.
26
+ * @returns {Promise<any>} - Une promesse qui se résout avec les données traitées.
27
+ */
28
+ export function runImportExportWorker(action, payload) {
29
+ return new Promise((resolve, reject) => {
30
+ const workerPath = path.resolve(process.cwd(), './src/workers/import-export-worker.js');
31
+ const worker = new Worker(workerPath);
32
+
33
+ worker.postMessage({ action, payload });
34
+
35
+ worker.on('message', (result) => {
36
+ if (result.success) {
37
+ resolve(result.data);
38
+ } else {
39
+ // Correction : On s'assure de toujours passer une chaîne de caractères à new Error()
40
+ const errorMessage = result.error || `Import/Export Worker failed with an unknown error. Action: ${action}.`;
41
+ reject(new Error(errorMessage));
42
+ }
43
+ worker.terminate();
44
+ });
45
+
46
+ worker.on('error', (err) => {
47
+ reject(err);
48
+ worker.terminate();
49
+ });
50
+
51
+ worker.on('exit', (code) => {
52
+ if (code !== 0) {
53
+ reject(new Error(`Import/Export Worker stopped with exit code ${code}`));
54
+ }
55
+ });
56
+ });
57
+ }
58
+ /** Exécute une tâche de cryptographie dans un worker thread.
59
+ * @param {('encrypt'|'decrypt'|'hash')} action - L'action à effectuer.
60
+ * @param {object} payload - Les données nécessaires pour l'action.
61
+ * @returns {Promise<any>} - Une promesse qui se résout avec le résultat (si pertinent).
62
+ */
63
+ export function runCryptoWorkerTask(action, payload) {
64
+ return new Promise((resolve, reject) => {
65
+ const workerPath = path.resolve(process.cwd(), './src/workers/crypto-worker.js');
66
+ const worker = new Worker(workerPath);
67
+
68
+ worker.postMessage({ action, payload });
69
+
70
+ worker.on('message', (result) => {
71
+ if (result.success) {
72
+ resolve(result.data); // Résout avec les données (ex: le hash) ou undefined si pas de retour
73
+ } else {
74
+ reject(new Error(result.error));
75
+ }
76
+ worker.terminate();
77
+ });
78
+
79
+ worker.on('error', (err) => {
80
+ reject(err);
81
+ worker.terminate();
82
+ });
83
+
84
+ worker.on('exit', (code) => {
85
+ if (code !== 0) {
86
+ reject(new Error(`Crypto Worker stopped with exit code ${code}`));
87
+ }
88
+ });
89
+ });
90
+ }
@@ -78,7 +78,7 @@ import {getAllPacks} from "../../packs.js";
78
78
  import {Config} from "../../config.js";
79
79
  import {profiles} from "../../../client/src/constants.js";
80
80
  import {registerRoutes, sendSseToUser} from "./data.routes.js";
81
- import {importJobs, modelsCache, mongoDBWhitelist} from "./data.core.js";
81
+ import {importJobs, modelsCache, mongoDBWhitelist, runCryptoWorkerTask, runImportExportWorker} from "./data.core.js";
82
82
  import readXlsxFile from "read-excel-file/node";
83
83
 
84
84
  let engine;
@@ -500,75 +500,6 @@ export const getAPILang = (langs) => {
500
500
  }, []).sort(((p,r) => p.quality < r.quality ? 1 : -1))?.[0].lang.split(/[-_]/)?.[0];
501
501
  }
502
502
 
503
- /**
504
- * Exécute une tâche d'import/export (parsing, stringify) dans un worker thread.
505
- * @param {('parse-json'|'parse-csv'|'stringify-json')} action - L'action à effectuer.
506
- * @param {object} payload - Les données nécessaires pour l'action.
507
- * @returns {Promise<any>} - Une promesse qui se résout avec les données traitées.
508
- */
509
- function runImportExportWorker(action, payload) {
510
- return new Promise((resolve, reject) => {
511
- const workerPath = path.resolve(process.cwd(), './src/workers/import-export-worker.js');
512
- const worker = new Worker(workerPath);
513
-
514
- worker.postMessage({ action, payload });
515
-
516
- worker.on('message', (result) => {
517
- if (result.success) {
518
- resolve(result.data);
519
- } else {
520
- // Correction : On s'assure de toujours passer une chaîne de caractères à new Error()
521
- const errorMessage = result.error || `Import/Export Worker failed with an unknown error. Action: ${action}.`;
522
- reject(new Error(errorMessage));
523
- }
524
- worker.terminate();
525
- });
526
-
527
- worker.on('error', (err) => {
528
- reject(err);
529
- worker.terminate();
530
- });
531
-
532
- worker.on('exit', (code) => {
533
- if (code !== 0) {
534
- reject(new Error(`Import/Export Worker stopped with exit code ${code}`));
535
- }
536
- });
537
- });
538
- }
539
- /** Exécute une tâche de cryptographie dans un worker thread.
540
- * @param {('encrypt'|'decrypt'|'hash')} action - L'action à effectuer.
541
- * @param {object} payload - Les données nécessaires pour l'action.
542
- * @returns {Promise<any>} - Une promesse qui se résout avec le résultat (si pertinent).
543
- */
544
- function runCryptoWorkerTask(action, payload) {
545
- return new Promise((resolve, reject) => {
546
- const workerPath = path.resolve(process.cwd(), './src/workers/crypto-worker.js');
547
- const worker = new Worker(workerPath);
548
-
549
- worker.postMessage({ action, payload });
550
-
551
- worker.on('message', (result) => {
552
- if (result.success) {
553
- resolve(result.data); // Résout avec les données (ex: le hash) ou undefined si pas de retour
554
- } else {
555
- reject(new Error(result.error));
556
- }
557
- worker.terminate();
558
- });
559
-
560
- worker.on('error', (err) => {
561
- reject(err);
562
- worker.terminate();
563
- });
564
-
565
- worker.on('exit', (code) => {
566
- if (code !== 0) {
567
- reject(new Error(`Crypto Worker stopped with exit code ${code}`));
568
- }
569
- });
570
- });
571
- }
572
503
 
573
504
  export function validateModelStructure(modelStructure) {
574
505
 
@@ -1353,6 +1284,7 @@ export async function onInit(defaultEngine) {
1353
1284
  packsCollection = getCollection("packs");
1354
1285
  }
1355
1286
  await registerRoutes(engine);
1287
+ logger = engine.getComponent(Logger);
1356
1288
 
1357
1289
  // set backup scheduler
1358
1290
  schedule.scheduleJob("0 2 * * *", jobDumpUserData);
@@ -1364,8 +1296,6 @@ export async function onInit(defaultEngine) {
1364
1296
  dt.setTime(dt.getTime()-1000*3600*24*14);
1365
1297
  await deleteData("request", {"$lt": ["$timestamp",dt.toISOString()]}, null, false);
1366
1298
  });
1367
- await scheduleWorkflowTriggers();
1368
-
1369
1299
  await scheduleAlerts();
1370
1300
 
1371
1301
  }
@@ -40,10 +40,10 @@ import {tutorialsConfig} from "../../../client/src/tutorials.js";
40
40
  import {
41
41
  cancelAlerts, deleteData,
42
42
  dumpUserData,
43
- editData, exportData,
43
+ editData, editModel, exportData,
44
44
  getModel, getResource,
45
45
  handleCustomEndpointRequest,
46
- handleDemoInitialization, importData, insertData, installPack,
46
+ handleDemoInitialization, importData, insertData, installPack, loadFromDump,
47
47
  patchData, searchData, validateModelStructure
48
48
  } from "./data.js";
49
49
  import process from "node:process";
@@ -10,15 +10,12 @@ export async function onInit(defaultEngine) {
10
10
  engine = defaultEngine;
11
11
  logger = engine.getComponent(Logger);
12
12
 
13
- const isProduction = process.env.NODE_ENV === 'production'
14
-
15
- modelsCollection = MongoDatabase.collection("models");
16
- datasCollection = MongoDatabase.collection("datas");
17
- filesCollection = MongoDatabase.collection("files");
18
- packsCollection = MongoDatabase.collection("packs");
13
+ modelsCollection = getCollection("models");
14
+ datasCollection = getCollection("datas");
15
+ filesCollection = getCollection("files");
16
+ packsCollection = getCollection("packs");
19
17
 
20
18
  logger.info("MongoDB collections loaded.");
21
-
22
19
  };
23
20
 
24
21
 
@@ -6,7 +6,7 @@ import crypto from "node:crypto";
6
6
  import ivm from 'isolated-vm';
7
7
 
8
8
  import {Logger} from "../gameObject.js";
9
- import {deleteData, insertData, patchData, searchData} from "./data/index.js";
9
+ import {deleteData, insertData, patchData, scheduleAlerts, searchData} from "./data/index.js";
10
10
  import {emailDefaultConfig, maxExecutionsByStep, maxWorkflowSteps} from "../constants.js";
11
11
  import {ChatOpenAI} from "@langchain/openai";
12
12
  import {ChatGoogleGenerativeAI} from "@langchain/google-genai";
@@ -21,6 +21,8 @@ import util from "node:util";
21
21
  let logger = null;
22
22
  export async function onInit(defaultEngine) {
23
23
  logger = defaultEngine.getComponent(Logger);
24
+
25
+ await scheduleWorkflowTriggers();
24
26
  }
25
27
 
26
28
  /**
@@ -48,7 +48,7 @@ function blobToFile(theBlob, fileName){
48
48
  }
49
49
 
50
50
  beforeAll(async () =>{
51
- Config.Set("modules", ["data", "mongodb", "file", "bucket", "workflow","user", "assistant"]);
51
+ Config.Set("modules", ["mongodb", "data", "file", "bucket", "workflow","user", "assistant"]);
52
52
  await initEngine();
53
53
  })
54
54