@intranefr/superbackend 1.4.4 → 1.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/index.js +16 -1
- package/package.json +5 -2
- package/public/sdk/ui-components.iife.js +191 -0
- package/sdk/ui-components/browser/src/index.js +228 -0
- package/src/controllers/admin.controller.js +89 -0
- package/src/controllers/adminHeadless.controller.js +82 -0
- package/src/controllers/adminScripts.controller.js +229 -0
- package/src/controllers/adminTerminals.controller.js +39 -0
- package/src/controllers/adminUiComponents.controller.js +315 -0
- package/src/controllers/adminUiComponentsAi.controller.js +34 -0
- package/src/controllers/orgAdmin.controller.js +286 -0
- package/src/controllers/uiComponentsPublic.controller.js +118 -0
- package/src/middleware/auth.js +7 -0
- package/src/middleware.js +115 -0
- package/src/models/HeadlessModelDefinition.js +10 -0
- package/src/models/ScriptDefinition.js +42 -0
- package/src/models/ScriptRun.js +22 -0
- package/src/models/UiComponent.js +29 -0
- package/src/models/UiComponentProject.js +26 -0
- package/src/models/UiComponentProjectComponent.js +18 -0
- package/src/routes/admin.routes.js +1 -0
- package/src/routes/adminHeadless.routes.js +6 -0
- package/src/routes/adminScripts.routes.js +21 -0
- package/src/routes/adminTerminals.routes.js +13 -0
- package/src/routes/adminUiComponents.routes.js +29 -0
- package/src/routes/llmUi.routes.js +26 -0
- package/src/routes/orgAdmin.routes.js +5 -0
- package/src/routes/uiComponentsPublic.routes.js +9 -0
- package/src/services/headlessExternalModels.service.js +292 -0
- package/src/services/headlessModels.service.js +26 -6
- package/src/services/scriptsRunner.service.js +259 -0
- package/src/services/terminals.service.js +152 -0
- package/src/services/terminalsWs.service.js +100 -0
- package/src/services/uiComponentsAi.service.js +312 -0
- package/src/services/uiComponentsCrypto.service.js +39 -0
- package/views/admin-headless.ejs +294 -24
- package/views/admin-organizations.ejs +365 -9
- package/views/admin-scripts.ejs +497 -0
- package/views/admin-terminals.ejs +328 -0
- package/views/admin-ui-components.ejs +709 -0
- package/views/admin-users.ejs +261 -4
- package/views/partials/dashboard/nav-items.ejs +3 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const uiComponentSchema = new mongoose.Schema(
|
|
4
|
+
{
|
|
5
|
+
code: {
|
|
6
|
+
type: String,
|
|
7
|
+
required: true,
|
|
8
|
+
unique: true,
|
|
9
|
+
index: true,
|
|
10
|
+
trim: true,
|
|
11
|
+
lowercase: true,
|
|
12
|
+
match: [/^[a-z][a-z0-9_-]{1,63}$/, 'Invalid component code'],
|
|
13
|
+
},
|
|
14
|
+
name: { type: String, required: true, trim: true },
|
|
15
|
+
|
|
16
|
+
html: { type: String, default: '' },
|
|
17
|
+
js: { type: String, default: '' },
|
|
18
|
+
css: { type: String, default: '' },
|
|
19
|
+
|
|
20
|
+
api: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
21
|
+
usageMarkdown: { type: String, default: '' },
|
|
22
|
+
|
|
23
|
+
version: { type: Number, default: 1 },
|
|
24
|
+
isActive: { type: Boolean, default: true, index: true },
|
|
25
|
+
},
|
|
26
|
+
{ timestamps: true, collection: 'ui_components' },
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
module.exports = mongoose.models.UiComponent || mongoose.model('UiComponent', uiComponentSchema);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const uiComponentProjectSchema = new mongoose.Schema(
|
|
4
|
+
{
|
|
5
|
+
projectId: {
|
|
6
|
+
type: String,
|
|
7
|
+
required: true,
|
|
8
|
+
unique: true,
|
|
9
|
+
index: true,
|
|
10
|
+
trim: true,
|
|
11
|
+
match: [/^prj_[a-z0-9]{8,32}$/, 'Invalid projectId'],
|
|
12
|
+
},
|
|
13
|
+
name: { type: String, required: true, trim: true },
|
|
14
|
+
|
|
15
|
+
isPublic: { type: Boolean, default: true, index: true },
|
|
16
|
+
apiKeyHash: { type: String, default: null },
|
|
17
|
+
|
|
18
|
+
allowedOrigins: { type: [String], default: [] },
|
|
19
|
+
|
|
20
|
+
isActive: { type: Boolean, default: true, index: true },
|
|
21
|
+
},
|
|
22
|
+
{ timestamps: true, collection: 'ui_component_projects' },
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
module.exports = mongoose.models.UiComponentProject ||
|
|
26
|
+
mongoose.model('UiComponentProject', uiComponentProjectSchema);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const uiComponentProjectComponentSchema = new mongoose.Schema(
|
|
4
|
+
{
|
|
5
|
+
projectId: { type: String, required: true, index: true },
|
|
6
|
+
componentCode: { type: String, required: true, index: true },
|
|
7
|
+
enabled: { type: Boolean, default: true, index: true },
|
|
8
|
+
},
|
|
9
|
+
{ timestamps: true, collection: 'ui_component_project_components' },
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
uiComponentProjectComponentSchema.index(
|
|
13
|
+
{ projectId: 1, componentCode: 1 },
|
|
14
|
+
{ unique: true },
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
module.exports = mongoose.models.UiComponentProjectComponent ||
|
|
18
|
+
mongoose.model('UiComponentProjectComponent', uiComponentProjectComponentSchema);
|
|
@@ -11,6 +11,7 @@ router.post('/users/register', adminController.registerUser);
|
|
|
11
11
|
router.get('/users/:id', adminController.getUser);
|
|
12
12
|
router.put('/users/:id/subscription', adminController.updateUserSubscription);
|
|
13
13
|
router.patch('/users/:id', adminController.updateUserPassword);
|
|
14
|
+
router.delete('/users/:id', adminController.deleteUser);
|
|
14
15
|
router.post('/users/:id/reconcile', adminController.reconcileUser);
|
|
15
16
|
router.post('/generate-token', adminController.generateToken);
|
|
16
17
|
|
|
@@ -13,6 +13,12 @@ router.post('/models', adminHeadlessController.createModel);
|
|
|
13
13
|
router.put('/models/:codeIdentifier', adminHeadlessController.updateModel);
|
|
14
14
|
router.delete('/models/:codeIdentifier', adminHeadlessController.deleteModel);
|
|
15
15
|
|
|
16
|
+
// External models (Mongo collections)
|
|
17
|
+
router.get('/external/collections', adminHeadlessController.listExternalCollections);
|
|
18
|
+
router.post('/external/infer', adminHeadlessController.inferExternalCollection);
|
|
19
|
+
router.post('/external/import', adminHeadlessController.importExternalModel);
|
|
20
|
+
router.post('/models/:codeIdentifier/sync', adminHeadlessController.syncExternalModel);
|
|
21
|
+
|
|
16
22
|
// Advanced JSON / bulk helpers
|
|
17
23
|
router.post('/models/validate', adminHeadlessController.validateModelDefinition);
|
|
18
24
|
router.post('/models/apply', adminHeadlessController.applyModelProposal);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
|
|
4
|
+
const { basicAuth } = require('../middleware/auth');
|
|
5
|
+
const controller = require('../controllers/adminScripts.controller');
|
|
6
|
+
|
|
7
|
+
router.use(basicAuth);
|
|
8
|
+
|
|
9
|
+
router.get('/', controller.listScripts);
|
|
10
|
+
router.post('/', controller.createScript);
|
|
11
|
+
router.get('/runs', controller.listRuns);
|
|
12
|
+
router.get('/runs/:runId', controller.getRun);
|
|
13
|
+
router.get('/runs/:runId/stream', controller.streamRun);
|
|
14
|
+
|
|
15
|
+
router.get('/:id', controller.getScript);
|
|
16
|
+
router.put('/:id', controller.updateScript);
|
|
17
|
+
router.delete('/:id', controller.deleteScript);
|
|
18
|
+
|
|
19
|
+
router.post('/:id/run', controller.runScript);
|
|
20
|
+
|
|
21
|
+
module.exports = router;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
|
|
4
|
+
const { basicAuth } = require('../middleware/auth');
|
|
5
|
+
const controller = require('../controllers/adminTerminals.controller');
|
|
6
|
+
|
|
7
|
+
router.use(basicAuth);
|
|
8
|
+
|
|
9
|
+
router.post('/sessions', controller.createSession);
|
|
10
|
+
router.get('/sessions', controller.listSessions);
|
|
11
|
+
router.delete('/sessions/:sessionId', controller.killSession);
|
|
12
|
+
|
|
13
|
+
module.exports = router;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
|
|
4
|
+
const { basicAuth } = require('../middleware/auth');
|
|
5
|
+
const adminUiComponentsController = require('../controllers/adminUiComponents.controller');
|
|
6
|
+
const adminUiComponentsAiController = require('../controllers/adminUiComponentsAi.controller');
|
|
7
|
+
|
|
8
|
+
router.use(basicAuth);
|
|
9
|
+
|
|
10
|
+
router.get('/projects', adminUiComponentsController.listProjects);
|
|
11
|
+
router.post('/projects', adminUiComponentsController.createProject);
|
|
12
|
+
router.get('/projects/:projectId', adminUiComponentsController.getProject);
|
|
13
|
+
router.put('/projects/:projectId', adminUiComponentsController.updateProject);
|
|
14
|
+
router.delete('/projects/:projectId', adminUiComponentsController.deleteProject);
|
|
15
|
+
router.post('/projects/:projectId/rotate-key', adminUiComponentsController.rotateProjectKey);
|
|
16
|
+
|
|
17
|
+
router.get('/components', adminUiComponentsController.listComponents);
|
|
18
|
+
router.post('/components', adminUiComponentsController.createComponent);
|
|
19
|
+
router.get('/components/:code', adminUiComponentsController.getComponent);
|
|
20
|
+
router.put('/components/:code', adminUiComponentsController.updateComponent);
|
|
21
|
+
router.delete('/components/:code', adminUiComponentsController.deleteComponent);
|
|
22
|
+
|
|
23
|
+
router.get('/projects/:projectId/components', adminUiComponentsController.listProjectAssignments);
|
|
24
|
+
router.post('/projects/:projectId/components/:code', adminUiComponentsController.setAssignment);
|
|
25
|
+
router.delete('/projects/:projectId/components/:code', adminUiComponentsController.deleteAssignment);
|
|
26
|
+
|
|
27
|
+
router.post('/ai/components/:code/propose', adminUiComponentsAiController.propose);
|
|
28
|
+
|
|
29
|
+
module.exports = router;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
|
|
4
|
+
const { basicAuth } = require('../middleware/auth');
|
|
5
|
+
const adminUiComponentsController = require('../controllers/adminUiComponents.controller');
|
|
6
|
+
|
|
7
|
+
router.use(basicAuth);
|
|
8
|
+
|
|
9
|
+
router.get('/projects', adminUiComponentsController.listProjects);
|
|
10
|
+
router.post('/projects', adminUiComponentsController.createProject);
|
|
11
|
+
router.get('/projects/:projectId', adminUiComponentsController.getProject);
|
|
12
|
+
router.put('/projects/:projectId', adminUiComponentsController.updateProject);
|
|
13
|
+
router.delete('/projects/:projectId', adminUiComponentsController.deleteProject);
|
|
14
|
+
router.post('/projects/:projectId/rotate-key', adminUiComponentsController.rotateProjectKey);
|
|
15
|
+
|
|
16
|
+
router.get('/components', adminUiComponentsController.listComponents);
|
|
17
|
+
router.post('/components', adminUiComponentsController.createComponent);
|
|
18
|
+
router.get('/components/:code', adminUiComponentsController.getComponent);
|
|
19
|
+
router.put('/components/:code', adminUiComponentsController.updateComponent);
|
|
20
|
+
router.delete('/components/:code', adminUiComponentsController.deleteComponent);
|
|
21
|
+
|
|
22
|
+
router.get('/projects/:projectId/components', adminUiComponentsController.listProjectAssignments);
|
|
23
|
+
router.post('/projects/:projectId/components/:code', adminUiComponentsController.setAssignment);
|
|
24
|
+
router.delete('/projects/:projectId/components/:code', adminUiComponentsController.deleteAssignment);
|
|
25
|
+
|
|
26
|
+
module.exports = router;
|
|
@@ -6,7 +6,12 @@ const orgAdminController = require('../controllers/orgAdmin.controller');
|
|
|
6
6
|
const asyncHandler = require('../utils/asyncHandler');
|
|
7
7
|
|
|
8
8
|
router.get('/', basicAuth, asyncHandler(orgAdminController.listOrgs));
|
|
9
|
+
router.post('/', basicAuth, asyncHandler(orgAdminController.createOrganization));
|
|
9
10
|
router.get('/:orgId', basicAuth, asyncHandler(orgAdminController.getOrg));
|
|
11
|
+
router.put('/:orgId', basicAuth, asyncHandler(orgAdminController.updateOrganization));
|
|
12
|
+
router.patch('/:orgId/disable', basicAuth, asyncHandler(orgAdminController.disableOrganization));
|
|
13
|
+
router.patch('/:orgId/enable', basicAuth, asyncHandler(orgAdminController.enableOrganization));
|
|
14
|
+
router.delete('/:orgId', basicAuth, asyncHandler(orgAdminController.deleteOrganization));
|
|
10
15
|
|
|
11
16
|
router.get('/:orgId/members', basicAuth, asyncHandler(orgAdminController.listMembers));
|
|
12
17
|
router.patch('/:orgId/members/:memberId', basicAuth, asyncHandler(orgAdminController.updateMember));
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
|
|
4
|
+
const uiComponentsPublicController = require('../controllers/uiComponentsPublic.controller');
|
|
5
|
+
|
|
6
|
+
router.get('/projects/:projectId/manifest', uiComponentsPublicController.getManifest);
|
|
7
|
+
router.get('/projects/:projectId/components/:code', uiComponentsPublicController.getComponent);
|
|
8
|
+
|
|
9
|
+
module.exports = router;
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const HeadlessModelDefinition = require('../models/HeadlessModelDefinition');
|
|
4
|
+
const { normalizeCodeIdentifier, computeSchemaHash } = require('./headlessModels.service');
|
|
5
|
+
|
|
6
|
+
function isObjectId(value) {
|
|
7
|
+
if (!value) return false;
|
|
8
|
+
if (value instanceof mongoose.Types.ObjectId) return true;
|
|
9
|
+
if (value && typeof value === 'object' && value._bsontype === 'ObjectID') return true;
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function detectFieldType(value) {
|
|
14
|
+
if (value === null || value === undefined) return null;
|
|
15
|
+
if (isObjectId(value)) return 'objectid';
|
|
16
|
+
if (value instanceof Date) return 'date';
|
|
17
|
+
if (Array.isArray(value)) return 'array';
|
|
18
|
+
const t = typeof value;
|
|
19
|
+
if (t === 'string') return 'string';
|
|
20
|
+
if (t === 'number') return 'number';
|
|
21
|
+
if (t === 'boolean') return 'boolean';
|
|
22
|
+
if (t === 'object') return 'object';
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function pickBestType(seenTypes) {
|
|
27
|
+
const types = new Set(Array.from(seenTypes || []).filter(Boolean));
|
|
28
|
+
if (types.size === 0) return { type: 'object', warning: 'No non-null sample values' };
|
|
29
|
+
if (types.size === 1) return { type: Array.from(types)[0], warning: null };
|
|
30
|
+
if (types.has('array')) return { type: 'array', warning: `Mixed types: ${Array.from(types).join('|')}` };
|
|
31
|
+
if (types.has('object')) return { type: 'object', warning: `Mixed types: ${Array.from(types).join('|')}` };
|
|
32
|
+
return { type: 'string', warning: `Mixed types: ${Array.from(types).join('|')}` };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function tryInferRefFromFieldName(fieldName, externalModelsByCollection) {
|
|
36
|
+
const name = String(fieldName || '').trim();
|
|
37
|
+
if (!name) return null;
|
|
38
|
+
|
|
39
|
+
const lower = name.toLowerCase();
|
|
40
|
+
if (!lower.endsWith('id') || lower === 'id') return null;
|
|
41
|
+
|
|
42
|
+
const stem = name.slice(0, -2);
|
|
43
|
+
const candidates = [stem, `${stem}s`, `${stem}es`];
|
|
44
|
+
for (const c of candidates) {
|
|
45
|
+
const match = externalModelsByCollection.get(String(c).toLowerCase());
|
|
46
|
+
if (match) return match;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function normalizeIndexFromMongo(idx) {
|
|
52
|
+
if (!idx || typeof idx !== 'object') return null;
|
|
53
|
+
const fields = idx.key;
|
|
54
|
+
if (!fields || typeof fields !== 'object') return null;
|
|
55
|
+
|
|
56
|
+
const options = { ...idx };
|
|
57
|
+
delete options.key;
|
|
58
|
+
delete options.v;
|
|
59
|
+
delete options.ns;
|
|
60
|
+
|
|
61
|
+
return { fields, options };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function listExternalCollections({ q, includeSystem } = {}) {
|
|
65
|
+
if (!mongoose.connection || !mongoose.connection.db) {
|
|
66
|
+
const err = new Error('Mongo connection not ready');
|
|
67
|
+
err.code = 'VALIDATION';
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const filter = {};
|
|
72
|
+
if (q) filter.name = { $regex: String(q), $options: 'i' };
|
|
73
|
+
|
|
74
|
+
const cursor = await mongoose.connection.db.listCollections(filter, { nameOnly: true });
|
|
75
|
+
const items = await cursor.toArray();
|
|
76
|
+
|
|
77
|
+
const out = [];
|
|
78
|
+
for (const c of items) {
|
|
79
|
+
const name = String(c && c.name ? c.name : '').trim();
|
|
80
|
+
if (!name) continue;
|
|
81
|
+
if (!includeSystem && name.startsWith('system.')) continue;
|
|
82
|
+
out.push({ name, type: 'collection' });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
out.sort((a, b) => a.name.localeCompare(b.name));
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function inferExternalModelFromCollection({ collectionName, sampleSize = 200 } = {}) {
|
|
90
|
+
if (!mongoose.connection || !mongoose.connection.db) {
|
|
91
|
+
const err = new Error('Mongo connection not ready');
|
|
92
|
+
err.code = 'VALIDATION';
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const collName = String(collectionName || '').trim();
|
|
97
|
+
if (!collName) {
|
|
98
|
+
const err = new Error('collectionName is required');
|
|
99
|
+
err.code = 'VALIDATION';
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const N = Math.max(1, Math.min(Number(sampleSize) || 200, 1000));
|
|
104
|
+
const coll = mongoose.connection.db.collection(collName);
|
|
105
|
+
|
|
106
|
+
let docs;
|
|
107
|
+
try {
|
|
108
|
+
docs = await coll.aggregate([{ $sample: { size: N } }]).toArray();
|
|
109
|
+
} catch {
|
|
110
|
+
docs = await coll.find({}).limit(N).toArray();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const externalModels = await HeadlessModelDefinition.find({ isActive: true, sourceType: 'external' })
|
|
114
|
+
.select({ codeIdentifier: 1, sourceCollectionName: 1 })
|
|
115
|
+
.lean();
|
|
116
|
+
|
|
117
|
+
const externalModelsByCollection = new Map();
|
|
118
|
+
for (const m of externalModels || []) {
|
|
119
|
+
const cn = String(m?.sourceCollectionName || '').trim();
|
|
120
|
+
const code = String(m?.codeIdentifier || '').trim();
|
|
121
|
+
if (cn && code) externalModelsByCollection.set(cn.toLowerCase(), code);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const perField = new Map();
|
|
125
|
+
const warnings = [];
|
|
126
|
+
|
|
127
|
+
for (const doc of docs || []) {
|
|
128
|
+
if (!doc || typeof doc !== 'object') continue;
|
|
129
|
+
for (const [k, v] of Object.entries(doc)) {
|
|
130
|
+
if (!k || k === '_id') continue;
|
|
131
|
+
const type = detectFieldType(v);
|
|
132
|
+
let stats = perField.get(k);
|
|
133
|
+
if (!stats) {
|
|
134
|
+
stats = { seenTypes: new Set(), objectIdCount: 0, nonNullCount: 0 };
|
|
135
|
+
perField.set(k, stats);
|
|
136
|
+
}
|
|
137
|
+
if (type) stats.seenTypes.add(type);
|
|
138
|
+
if (type === 'objectid') stats.objectIdCount += 1;
|
|
139
|
+
if (v !== null && v !== undefined) stats.nonNullCount += 1;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const fields = [];
|
|
144
|
+
for (const [name, stats] of perField.entries()) {
|
|
145
|
+
const { type, warning } = pickBestType(stats.seenTypes);
|
|
146
|
+
|
|
147
|
+
if (warning) warnings.push(`Field ${name}: ${warning}`);
|
|
148
|
+
|
|
149
|
+
if (type === 'objectid') {
|
|
150
|
+
const refModelCode = tryInferRefFromFieldName(name, externalModelsByCollection);
|
|
151
|
+
if (refModelCode) {
|
|
152
|
+
fields.push({ name, type: 'ref', required: false, unique: false, refModelCode });
|
|
153
|
+
} else {
|
|
154
|
+
fields.push({ name, type: 'string', required: false, unique: false });
|
|
155
|
+
}
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (type === 'date') {
|
|
160
|
+
fields.push({ name, type: 'date', required: false, unique: false });
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (type === 'array') {
|
|
165
|
+
fields.push({ name, type: 'array', required: false, unique: false });
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (type === 'object') {
|
|
170
|
+
fields.push({ name, type: 'object', required: false, unique: false });
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (type === 'number' || type === 'boolean' || type === 'string') {
|
|
175
|
+
fields.push({ name, type, required: false, unique: false });
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
fields.push({ name, type: 'object', required: false, unique: false });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
fields.sort((a, b) => a.name.localeCompare(b.name));
|
|
183
|
+
|
|
184
|
+
let indexes = [];
|
|
185
|
+
try {
|
|
186
|
+
const idx = await coll.indexes();
|
|
187
|
+
indexes = (idx || []).map(normalizeIndexFromMongo).filter(Boolean);
|
|
188
|
+
} catch {
|
|
189
|
+
indexes = [];
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const fieldsHash = computeSchemaHash({ fields, indexes });
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
collectionName: collName,
|
|
196
|
+
fields,
|
|
197
|
+
indexes,
|
|
198
|
+
warnings,
|
|
199
|
+
stats: {
|
|
200
|
+
sampled: (docs || []).length,
|
|
201
|
+
maxSampleSize: N,
|
|
202
|
+
fields: fields.length,
|
|
203
|
+
},
|
|
204
|
+
fieldsHash,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function createOrUpdateExternalModel({ collectionName, codeIdentifier, displayName, sampleSize } = {}) {
|
|
209
|
+
const cn = String(collectionName || '').trim();
|
|
210
|
+
if (!cn) {
|
|
211
|
+
const err = new Error('collectionName is required');
|
|
212
|
+
err.code = 'VALIDATION';
|
|
213
|
+
throw err;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const code = normalizeCodeIdentifier(codeIdentifier);
|
|
217
|
+
if (!code.startsWith('ext_')) {
|
|
218
|
+
const err = new Error('External model codeIdentifier must start with ext_');
|
|
219
|
+
err.code = 'VALIDATION';
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const name = String(displayName || code).trim();
|
|
224
|
+
if (!name) {
|
|
225
|
+
const err = new Error('displayName is required');
|
|
226
|
+
err.code = 'VALIDATION';
|
|
227
|
+
throw err;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const inferred = await inferExternalModelFromCollection({ collectionName: cn, sampleSize });
|
|
231
|
+
|
|
232
|
+
const existing = await HeadlessModelDefinition.findOne({ codeIdentifier: code, isActive: true });
|
|
233
|
+
if (!existing) {
|
|
234
|
+
const doc = await HeadlessModelDefinition.create({
|
|
235
|
+
codeIdentifier: code,
|
|
236
|
+
displayName: name,
|
|
237
|
+
description: '',
|
|
238
|
+
fields: inferred.fields,
|
|
239
|
+
indexes: inferred.indexes,
|
|
240
|
+
fieldsHash: inferred.fieldsHash,
|
|
241
|
+
version: 1,
|
|
242
|
+
previousFields: [],
|
|
243
|
+
previousIndexes: [],
|
|
244
|
+
sourceType: 'external',
|
|
245
|
+
sourceCollectionName: cn,
|
|
246
|
+
isExternal: true,
|
|
247
|
+
inference: {
|
|
248
|
+
enabled: true,
|
|
249
|
+
lastInferredAt: new Date(),
|
|
250
|
+
sampleSize: Number(sampleSize) || null,
|
|
251
|
+
warnings: inferred.warnings || [],
|
|
252
|
+
stats: inferred.stats || null,
|
|
253
|
+
},
|
|
254
|
+
isActive: true,
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
return { created: true, item: doc.toObject(), inference: inferred };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
existing.displayName = name;
|
|
261
|
+
existing.sourceType = 'external';
|
|
262
|
+
existing.sourceCollectionName = cn;
|
|
263
|
+
existing.isExternal = true;
|
|
264
|
+
|
|
265
|
+
const newHash = inferred.fieldsHash;
|
|
266
|
+
if (newHash !== existing.fieldsHash) {
|
|
267
|
+
existing.previousFields = existing.fields;
|
|
268
|
+
existing.previousIndexes = existing.indexes;
|
|
269
|
+
existing.fields = inferred.fields;
|
|
270
|
+
existing.indexes = inferred.indexes;
|
|
271
|
+
existing.fieldsHash = newHash;
|
|
272
|
+
existing.version = Number(existing.version || 1) + 1;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
existing.inference = {
|
|
276
|
+
enabled: true,
|
|
277
|
+
lastInferredAt: new Date(),
|
|
278
|
+
sampleSize: Number(sampleSize) || null,
|
|
279
|
+
warnings: inferred.warnings || [],
|
|
280
|
+
stats: inferred.stats || null,
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
await existing.save();
|
|
284
|
+
|
|
285
|
+
return { created: false, item: existing.toObject(), inference: inferred };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
module.exports = {
|
|
289
|
+
listExternalCollections,
|
|
290
|
+
inferExternalModelFromCollection,
|
|
291
|
+
createOrUpdateExternalModel,
|
|
292
|
+
};
|
|
@@ -89,6 +89,18 @@ function getMongoCollectionName(codeIdentifier) {
|
|
|
89
89
|
return `${MODEL_COLLECTION_PREFIX}${code}`;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
function isExternalDefinition(def) {
|
|
93
|
+
return def && (def.sourceType === 'external' || def.isExternal === true);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function getCollectionNameForDefinition(def) {
|
|
97
|
+
if (isExternalDefinition(def)) {
|
|
98
|
+
const cn = String(def.sourceCollectionName || '').trim();
|
|
99
|
+
return cn || getMongoCollectionName(def.codeIdentifier);
|
|
100
|
+
}
|
|
101
|
+
return getMongoCollectionName(def.codeIdentifier);
|
|
102
|
+
}
|
|
103
|
+
|
|
92
104
|
function buildSchemaFromDefinition(def) {
|
|
93
105
|
const schemaShape = {};
|
|
94
106
|
for (const field of def.fields || []) {
|
|
@@ -99,12 +111,14 @@ function buildSchemaFromDefinition(def) {
|
|
|
99
111
|
schemaShape[fieldName] = toMongooseField(field);
|
|
100
112
|
}
|
|
101
113
|
|
|
102
|
-
|
|
103
|
-
|
|
114
|
+
if (!isExternalDefinition(def)) {
|
|
115
|
+
schemaShape._headlessModelCode = { type: String, default: def.codeIdentifier, index: true };
|
|
116
|
+
schemaShape._headlessSchemaVersion = { type: Number, default: def.version, index: true };
|
|
117
|
+
}
|
|
104
118
|
|
|
105
119
|
const schema = new mongoose.Schema(schemaShape, {
|
|
106
120
|
timestamps: true,
|
|
107
|
-
collection:
|
|
121
|
+
collection: getCollectionNameForDefinition(def),
|
|
108
122
|
strict: false,
|
|
109
123
|
});
|
|
110
124
|
|
|
@@ -254,6 +268,8 @@ async function disableModelDefinition(codeIdentifier) {
|
|
|
254
268
|
const modelCache = new Map();
|
|
255
269
|
|
|
256
270
|
async function ensureAutoMigration(modelDef) {
|
|
271
|
+
if (isExternalDefinition(modelDef)) return;
|
|
272
|
+
|
|
257
273
|
const collectionName = getMongoCollectionName(modelDef.codeIdentifier);
|
|
258
274
|
const coll = mongoose.connection.collection(collectionName);
|
|
259
275
|
|
|
@@ -318,7 +334,8 @@ async function getDynamicModel(codeIdentifier) {
|
|
|
318
334
|
throw err;
|
|
319
335
|
}
|
|
320
336
|
|
|
321
|
-
const
|
|
337
|
+
const collectionName = getCollectionNameForDefinition(def);
|
|
338
|
+
const cacheKey = `${def.codeIdentifier}:${def.version}:${def.fieldsHash}:${collectionName}`;
|
|
322
339
|
const cached = modelCache.get(cacheKey);
|
|
323
340
|
if (cached) return cached;
|
|
324
341
|
|
|
@@ -334,8 +351,10 @@ async function getDynamicModel(codeIdentifier) {
|
|
|
334
351
|
const schema = buildSchemaFromDefinition(def);
|
|
335
352
|
const Model = mongoose.model(modelName, schema);
|
|
336
353
|
|
|
337
|
-
|
|
338
|
-
|
|
354
|
+
if (!isExternalDefinition(def)) {
|
|
355
|
+
await ensureAutoMigration(def);
|
|
356
|
+
await ensureIndexesBestEffort(Model);
|
|
357
|
+
}
|
|
339
358
|
|
|
340
359
|
modelCache.set(cacheKey, Model);
|
|
341
360
|
return Model;
|
|
@@ -346,6 +365,7 @@ module.exports = {
|
|
|
346
365
|
normalizeCodeIdentifier,
|
|
347
366
|
getMongooseModelName,
|
|
348
367
|
getMongoCollectionName,
|
|
368
|
+
getCollectionNameForDefinition,
|
|
349
369
|
computeSchemaHash,
|
|
350
370
|
listModelDefinitions,
|
|
351
371
|
getModelDefinitionByCode,
|