-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsolutionBuilder.js
More file actions
executable file
·969 lines (837 loc) · 32.5 KB
/
solutionBuilder.js
File metadata and controls
executable file
·969 lines (837 loc) · 32.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
if(typeof window === 'undefined'){
fs = require('fs');
path = require('path'); // CommonJS
JSZip = require('jszip'); // CommonJS
yaml = require('js-yaml'); //
const { Blob } = require('buffer');
}
const mime = require('mime-types');
const { v4: uuidv4 } = require('uuid');
// solution-builder.js
// Base URL for fetching files from the repository
async function selectLocalFolder() {
try {
const dirHandle = await window.showDirectoryPicker();
DIRECTORY = dirHandle; // Store directory handle instead of a URL
init();
} catch (err) {
console.error('Error selecting folder:', err);
}
}
function isHttpUrl(str) {
return typeof str == 'string' && (str.startsWith('http://') || str.startsWith('https://'));
}
async function fetchJSON(handleOrUrl,DIRECTORY=null, rootPath = '') {
// Case 1: GitHub fetch (browser or Node with fetch polyfill)
if (isHttpUrl(handleOrUrl)) {
const response = await fetch(handleOrUrl, { headers: getHeaders() });
if (!response.ok) throw new Error(`Failed to fetch ${handleOrUrl}: ${response.statusText}`);
const data = await response.json();
return JSON.parse(atob(data.content));
}
// Case 2: Browser File System Access API (directory handle)
else if (typeof DIRECTORY !== 'undefined' && typeof DIRECTORY !== 'string' && DIRECTORY) {
try {
if (typeof handleOrUrl == 'string') {
// Split the path into parts (e.g., "subfolder/file.txt" -> ["subfolder", "file.txt"])
const pathParts = handleOrUrl.split('/').filter(part => part.length > 0);
let currentDir = DIRECTORY;
// Navigate directories if there are multiple parts
for (let i = 0; i < pathParts.length - 1; i++) {
currentDir = await currentDir.getDirectoryHandle(pathParts[i], { create: false });
}
// Get the file handle from the final directory
const fileName = pathParts[pathParts.length - 1];
fileHandle = await currentDir.getFileHandle(fileName);
} else {
// Assume handleOrUrl is an object with a handle property (file or directory handle)
fileHandle = handleOrUrl;
}
const file = await fileHandle.getFile();
const text = await file.text();
return JSON.parse(text);
} catch (error) {
console.error(`File not found: ${handleOrUrl}`);
return null;
}
}
// Case 3: Local file path (Node.js)
else if (typeof window === 'undefined' && typeof handleOrUrl === 'string') {
try {
fs.accessSync(handleOrUrl, fs.constants.F_OK);
} catch (error) {
console.error(`File not found: ${handleOrUrl}`);
return null;
}
const text = fs.readFileSync(handleOrUrl, 'utf8');
// Create a timeout Promise that resolves after a short delay
const js_obj = JSON.parse(text);
return js_obj
}
// Fallback: Throw an error if no valid case is matched
else {
throw new Error('Invalid environment or input for fetchJSON');
}
}
function getBePackageConf(name, definition, branch){
if (typeof definition === 'undefined'){
console.log(name + " be has no definition")
return {}
}
let pip = "";
// overide the branch if a branch is specified in the source
if (definition.hasOwnProperty("branch")) {
branch = definition.branch;
}
if (branch == 'released'){
pip = definition.package + "~=" + definition.version;
}else{
pip = "git+" + definition.git + ".git@" + branch + "#egg="+ definition.package;
}
return {
"name": name,
"pip" : pip
}
}
function getServiceConf(name, definition, services = {}){
if (typeof definition === 'undefined'){
console.log(name + " service has no definition")
return {}
}
if(!definition.hasOwnProperty('path') ){
console.log(name + " service has no path ")
return {}
}
if ( services[name] === undefined){
services[name]= {};
}
services[name] = {
"path": definition['path'],
}
if(definition.hasOwnProperty('env_file')){
if(!services[name].hasOwnProperty('env_file')){
services[name]['env_file'] = []
}
for(let env_file in definition['env_file']){
if(!services[name]['env_file'].includes(definition['env_file'][env_file])){
services[name]['env_file'].push(definition['env_file'][env_file])
}
}
}
if(definition.hasOwnProperty('env_contrib')){
for(let contrib in definition['env_contrib']){
if ( services[contrib] === undefined){
services[contrib] = {}
}
services[contrib]['env_file'] = [...(services[contrib]['env_file'] || []), ...definition['env_contrib'][contrib]]
}
}
return services
}
function getFePackageConf(name, definition, branch){
if (typeof definition === 'undefined'){
console.log(name + " fe has no definition")
return {}
}
let npm = ''
if (branch == 'released'){
npm = definition.package + "@>=" + definition.version;
}else{
npm = definition.package + "@" + definition.git + "#" + branch
}
return {
"name": name,
"npm" : npm
}
}
function makeCoreModuleConfiguration(menusDict) {
const config = {
menus: Object.values(menusDict).sort((a, b) => (a.position || 0) - (b.position || 0))
};
return [
{
model: 'core.moduleconfiguration',
fields: {
id: uuidv4(),
module: 'fe-core',
version: '1',
config: JSON.stringify(config, null, 2),
is_exposed: true,
layer: 'fe'
}
}
];
}
// Function to merge and sort fixtures
async function mergeAndSortFixtures(inputFiles, output) {
// Ensure output directory exists
// Object to store fixtures grouped by model
const fixturesByModel = {};
// Process each input file
for (const filePath of inputFiles) {
const filename = path.basename(filePath);
console.log(`Processing file: ${filename}`);
const data = await fetchJSON(filePath);
if (data){
// Group entries by model
for (const entry of data) {
const model = entry.model;
if (!fixturesByModel[model]) {
fixturesByModel[model] = [];
}
fixturesByModel[model].push(entry);
}
}
}
if (output['fixtures/roles.json']) {
if (!fixturesByModel['core.role']) {
fixturesByModel['core.role'] = [];
}
fixturesByModel['core.role'].push(...output['fixtures/roles.json']);
delete output['fixtures/roles.json'];
}
if (output['fixtures/roles-right.json']) {
if (!fixturesByModel['core.roleright']) {
fixturesByModel['core.roleright'] = [];
}
fixturesByModel['core.roleright'].push(...output['fixtures/roles-right.json']);
delete output['fixtures/roles-right.json'];
}
// Sort and save each model's fixtures
for (const model in fixturesByModel) {
// Sort entries by pk (primary key) if it exists
fixturesByModel[model].sort((a, b) => {
const pkA = a.pk || 0;
const pkB = b.pk || 0;
return pkA - pkB;
});
// Create output file path
const filename = `${model.replace('.', '_')}.json`;
// Write sorted fixtures to file
output[`fixtures/${filename}`] = fixturesByModel[model];
}
return output;
}
function mergeRoleDictionaries(mergedMenusDict, resultMenusDict) {
for (const roleCode in mergedMenusDict) {
const role = mergedMenusDict[roleCode];
const permissions = role.permissions || [];
if (roleCode in resultMenusDict) {
// Role exists, merge permissions without duplicates
const existingPermissionCodes = new Set(
resultMenusDict[roleCode].permissions.map(p => p.code)
);
for (const perm of permissions) {
if (!existingPermissionCodes.has(perm.code)) {
resultMenusDict[roleCode].permissions.push(perm);
existingPermissionCodes.add(perm.code);
}
}
} else {
// Role doesn't exist, add it directly
resultMenusDict[roleCode] = {
roleName: role.roleName,
code: roleCode,
permissions: [...permissions] // Create a new array to avoid reference issues
};
}
}
return resultMenusDict;
}
function mergeMenuDictionaries(mergedMenusDict, resultMenusDict) {
// Helper function to merge entries
function mergeentries(existingentries, newentries, mainMenuId) {
const entries = existingentries ? [...existingentries] : [];
if (!newentries) return entries;
// Remove entries from other main menus to ensure uniqueness
function removeSubmenuFromOtherMenus(submenuId, targetMainMenuId) {
for (const menuId in mergedMenusDict) {
if (menuId !== targetMainMenuId && mergedMenusDict[menuId].entries) {
mergedMenusDict[menuId].entries = mergedMenusDict[menuId].entries.filter(
submenu => submenu.id !== submenuId
);
}
}
}
// Merge or add new entries
newentries.forEach(newSubmenu => {
removeSubmenuFromOtherMenus(newSubmenu.id, mainMenuId);
const existingIndex = entries.findIndex(submenu => submenu.id === newSubmenu.id);
if (existingIndex !== -1) {
// Update existing submenu
entries[existingIndex] = { ...newSubmenu };
} else {
// Add new submenu
entries.push({ ...newSubmenu });
}
});
return entries;
}
// Iterate through resultMenusDict to merge into mergedMenusDict
for (const menuId in resultMenusDict) {
const resultMenu = resultMenusDict[menuId];
const existingMenu = mergedMenusDict[menuId] || {};
// Merge main menu fields, preserving existing entries if not provided in result
mergedMenusDict[menuId] = {
position: resultMenu.position !== undefined ? resultMenu.position : existingMenu.position,
id: menuId,
name: resultMenu.name !== undefined ? resultMenu.name : existingMenu.name,
icon: resultMenu.icon !== undefined ? resultMenu.icon : existingMenu.icon,
description: resultMenu.description !== undefined ? resultMenu.description : existingMenu.description,
entries: mergeentries(existingMenu.entries, resultMenu.entries, menuId)
};
}
return mergedMenusDict;
}
function cleanMenuDictionaries(menusDict) {
// Iterate through resultMenusDict to merge into mergedMenusDict
for (const menuId in menusDict) {
if(menusDict[menuId].entries.length === 0 || menusDict[menuId].name === undefined){
delete menusDict[menuId];
}
}
return menusDict;
}
function transformComposeContent(composeContent) {
let object = {'include': []}
// Iterate through each key in the composeContent object
for (const [key, value] of Object.entries(composeContent)) {
const line = {'path': value.path};
// Handle env_file section
if (value.env_file && value.env_file.length > 0) {
line['env_file'] = [...value.env_file];
}
object['include'].push(line)
}
return object;
}
async function processSolutions(
solutionFile,
directoryPath,
permissionMap,
branch = 'develop'
)
{
const solutionFilePath = getAbsolutePath(typeof solutionFile === 'string' ? solutionFile : '', '', false);
let solutionJson = {};
try {
solutionJson = JSON.parse(fs.readFileSync(solutionFile, 'utf8'));
} catch (e) {
console.warn('⚠️ Failed to parse root solution JSON file:', e.message);
}
let logoPath = null;
if (solutionJson?.moduleConfiguration?.logo) {
logoPath = path.resolve(path.dirname(solutionFilePath), solutionJson.moduleConfiguration.logo);
}
let themePath = null;
if (solutionJson?.moduleConfiguration?.theme) {
themePath = path.resolve(path.dirname(solutionFilePath), solutionJson.moduleConfiguration.theme);
}
let merged = await mergeSolutions(solutionFile, directoryPath, permissionMap);
let result = {};
// Commented out buggy for loop that tries to merge modules as solutions
/*
for (let key in merged.moduleRefDict || {}) {
const depPath = getAbsolutePath(merged.moduleRefDict[key], solutionFilePath);
result = await mergeSolutions(
depPath,
directoryPath,
permissionMap,
);
// Merge roles
merged.rolesDict = mergeRoleDictionaries(merged.rolesDict, result.rolesDict)
merged.menusDict = mergeMenuDictionaries(merged.menusDict, result.menusDict);
Object.assign(merged.moduleRefDict, result.moduleRefDict);
Array.prototype.push.apply(merged.bePackagesList,result.bePackagesList);
Object.assign(merged.bePackagesDefDict, result.bePackagesDefDict);
Array.prototype.push.apply(merged.fePackagesList,result.fePackagesList);
Array.prototype.push.apply(merged.locales,result.locales);
Object.assign(merged.fePackagesDefDict, result.fePackagesDefDict);
Array.prototype.push.apply(merged.servicesList,result.servicesList);
for (let idx in result.servicesDefDict){
service = merged.servicesList[idx]
merged.servicesDefDict = getServiceConf(service, result.servicesDefDict[service], services)
}
Array.prototype.push.apply(merged.initData,result.initData);
for(let data of result.initData){
merged.initData.add(getAbsolutePath(data, solutionFilePath));
}
}
*/
merged.menusDict = cleanMenuDictionaries(merged.menusDict)
// Generate module-level permissions map
let modulePermissionsMap = {};
const includedModules = Object.keys(merged.moduleRefDict);
for (const permKey in permissionMap) {
const module = permKey.split('.')[0];
if (includedModules.includes(module)) {
if (!modulePermissionsMap[module]) {
modulePermissionsMap[module] = {};
}
modulePermissionsMap[module][permKey] = permissionMap[permKey];
}
}
const assemblyBranch = merged.bePackagesDefDict['assembly']?.branch || 'develop';
let PIPModules = new Set()
merged.bePackagesList = merged.bePackagesList.filter((item, index) => merged.bePackagesList.indexOf(item) === index)
for (let idx in merged.bePackagesList){
bePackage = merged.bePackagesList[idx]
PIPModules.add(getBePackageConf(bePackage, merged.bePackagesDefDict[bePackage], assemblyBranch))
}
let NPMModules = new Set()
merged.fePackagesList = merged.fePackagesList.filter((item, index) => merged.fePackagesList.indexOf(item) === index)
for (let idx in merged.fePackagesList){
fePackage = merged.fePackagesList[idx]
NPMModules.add(getFePackageConf(fePackage, merged.fePackagesDefDict[fePackage], assemblyBranch))
}
let services = {}
for (let idx in merged.servicesList){
service = merged.servicesList[idx]
services = getServiceConf(service, merged.servicesDefDict[service], services)
}
output = {}
output['module_permissions_map.json'] = modulePermissionsMap;
// TODO manage the language in a better way
if(NPMModules.size>0){
output['fe-openimis.json'] ={
"modules": [...NPMModules],
"locales": [...merged.locales]
};
}
if(services){
output['compose.yml'] = transformComposeContent(services);
}
if(PIPModules.size>0){
output['be-openimis.json'] ={"modules": [...PIPModules]};
}
if (Object.keys(merged.menusDict).length > 0) {
const coreModuleConfig = makeCoreModuleConfiguration(merged.menusDict);
// Inject logo/theme using resolved paths
await injectLogoTheme(coreModuleConfig[0], logoPath, themePath);
output['fixtures/module-configuration-core.json'] = coreModuleConfig;
}
if (Object.keys(merged.rolesDict).length > 0) {
const transformed = transformRolesToFixture(merged.rolesDict);
output['fixtures/roles.json'] = transformed.roles;
output['fixtures/roles-right.json'] = transformed.rolesRight;
}
// merging all fixture
output = await mergeAndSortFixtures(merged.initData, output);
// sorting fixture by model
// adding fixture file to output
if(Object.keys(services).length>0){
output['compose.yml'] = services;
}
return { output, modules: Object.keys(merged.moduleRefDict), assemblyBranch }
}
async function mergeSolutions(
solutionFile,
directoryPath,
permissionMap,
rolesDict = {},
menusDict = {},
moduleRefDict = {},
bePackagesList = new Set(), bePackagesDefDict = {},
fePackagesList = new Set(), fePackagesDefDict = {},
locales = new Set(),
servicesList = new Set(), servicesDefDict = {},
initData = new Set())
{
let solutionFilePath = ''
let solution = null
if ( typeof window === 'undefined' && typeof solutionFile === 'string' ){
solutionPath = getAbsolutePath(solutionFile, directoryPath)
solution = await fetchJSON(solutionPath);
solutionFilePath = path.dirname(solutionPath);
} else if (typeof FileSystemFileHandle !== 'undefined' && solutionFile == '[object FileSystemFileHandle]'){
solution = await fetchJSON(solutionFile, directoryPath);
solutionPath = solutionFile
solutionFilePath = 'solution/solutions';
} else if (typeof solutionFile === 'object'){
solution = solutionFile;
solutionFilePath = typeof directoryPath === 'string'?directoryPath:''
}
if (solution.toString() == '[object Promise]' || !solution) {
console.warn(`Failed to load solution file: ${solutionFile}`);
return { rolesDict, menusDict, moduleRefDict, bePackagesList, bePackagesDefDict, fePackagesList, fePackagesDefDict, locales, servicesList, servicesDefDict, initData };
}
// Process solutions
const solutions = solution.solutions || [];
for (const dep of solutions) {
const depPath = getAbsolutePath(dep, solutionFilePath);
const result = await mergeSolutions(
depPath,
directoryPath,
permissionMap,
rolesDict,
menusDict,
moduleRefDict,
bePackagesList, bePackagesDefDict,
fePackagesList, fePackagesDefDict,
locales,
servicesList, servicesDefDict,
initData,
);
rolesDict = result.rolesDict;
menusDict = result.menusDict;
moduleRefDict = result.moduleRefDict;
bePackagesList = result.bePackagesList;
bePackagesDefDict = result.bePackagesDefDict;
fePackagesList = result.fePackagesList;
locales = result.locales;
fePackagesDefDict = result.fePackagesDefDict;
servicesList = result.servicesList;
servicesDefDict = result.servicesDefDict;
for(let idx in result.initData){
initData.add(getAbsolutePath(result.initData[idx], depPath));
}
}
// Process modules
for (let key in solution.modules || {} ) {
const modulePath = getAbsolutePath(solution.modules[key], solutionFilePath);
moduleRefDict[key] = modulePath;
}
fePackagesList = [...(solution.fePackages || []), ...fePackagesList]
for (let key in solution.fePackageDefinitions || {}) {
fePackagesDefDict[key] = solution.fePackageDefinitions[key];
}
bePackagesList = [...(solution.bePackages || []), ...bePackagesList]
for (let key in solution.bePackageDefinitions || {}) {
bePackagesDefDict[key] = solution.bePackageDefinitions[key];
}
// Merge arrays and remove duplicates based on locale.intl
locales = [...(solution.locales || []), ...locales];
// Use reduce to create a dictionary with intl as the key
const localesDict = locales.reduce((dict, locale) => {
dict[locale.intl] = locale;
return dict;
}, {});
// Convert dictionary values back to an array
locales = Object.values(localesDict);
servicesList = [...(solution.services || []), ...servicesList]
for (let key in solution.serviceDefinitions || {}) {
servicesDefDict[key] = solution.serviceDefinitions[key];
}
for(let idx in solution.initData){
initData.add(getAbsolutePath(solution.initData[idx], solutionFilePath));
}
// Merge roles
rolesDict = mergeRolesData(solution.roles || [], permissionMap, rolesDict);
// Merge menus
menusDict = mergeMenusData(solution.menus || [], menusDict);
return {
rolesDict,
menusDict,
moduleRefDict,
bePackagesList, bePackagesDefDict,
fePackagesList, fePackagesDefDict,
locales,
servicesList, servicesDefDict,
initData
};
}
function getAbsolutePath(relativePath, basePath, withFile=true) {
if( typeof window === 'undefined'){
filePath = path.isAbsolute(relativePath) ? relativePath : path.join(basePath, relativePath)
if(withFile){
return filePath;
}else{
return path.dirname(filePath)
}
}else{
const pathParts = relativePath.split('/').filter(part => part.length > 0);
let dirParts = basePath.split('/').filter(part => part.length > 0);
for (let i = 0; i < pathParts.length; i++) {
const part = pathParts[i];
if (part === '..') {
// Move up to root if we're not already there
if (dirParts.length !== 0) {
// In this simplified model, we reset to root; no parent handle available
dirParts.pop();
} else {
throw new Error("Cannot go above root directory");
}
} else if (part !== '.') { // Ignore '.'
// If it's the last part, treat it as a file; otherwise, a directory
dirParts.push(part)
}
}
if(withFile){
return dirParts.join('/');
}else{
return dirParts.slice(0, -1).join("/");
}
}
}
function mergeRolesData(roles, permissionMap, roleDict) {
for (const role of roles) {
const roleCode = role.code;
const permissions = role.permissions || [];
const mappedPermissions = permissions
.filter(permission => {
const code = permissionMap[permission];
return code; // only keep permissions that have a truthy code
})
.map(permission => ({
name: permission,
code: permissionMap[permission]
}));
if (mappedPermissions.length === 0) {
continue;
}
if (roleCode in roleDict) {
// Merge permissions, avoiding duplicates based on code
const existingPermissionCodes = new Set(
roleDict[roleCode].permissions.map(p => p.code)
);
for (const perm of mappedPermissions) {
if (!existingPermissionCodes.has(perm.code)) {
roleDict[roleCode].permissions.push(perm);
existingPermissionCodes.add(perm.code);
}
}
} else {
roleDict[roleCode] = {
roleName: role.roleName,
code: roleCode,
permissions: mappedPermissions
};
}
}
return roleDict;
}
function mergeMenusData(menus, menuDict) {
// Helper function to find and remove submenu from all main menus
function removeSubmenuFromOtherMenus(submenuId, targetMainMenuId) {
for (const mainMenuId in menuDict) {
if (mainMenuId !== targetMainMenuId && menuDict[mainMenuId].entries) {
menuDict[mainMenuId].entries = menuDict[mainMenuId].entries.filter(
submenu => submenu.id !== submenuId
);
}
}
}
for (const menu of menus) {
// Handle submenu payload (has mainMenu field)
if (menu.mainMenu) {
const mainMenuId = menu.mainMenu;
const submenu = {
position: menu.position,
id: menu.id,
name: menu.name,
icon: menu.icon,
route: menu.route,
text: menu.text,
description: menu.description,
withDivider: menu.withDivider
};
// Create minimal main menu if it doesn't exist
if (!menuDict[mainMenuId]) {
menuDict[mainMenuId] = {
id: mainMenuId,
entries: []
};
}
// Remove this submenu from other main menus
removeSubmenuFromOtherMenus(menu.id, mainMenuId);
// Add submenu to the target main menu
if (!menuDict[mainMenuId].entries) {
menuDict[mainMenuId].entries = [];
}
// Check if submenu already exists
const existingSubmenuIndex = menuDict[mainMenuId].entries.findIndex(
sm => sm.id === menu.id
);
if (existingSubmenuIndex !== -1) {
// Update existing submenu
menuDict[mainMenuId].entries[existingSubmenuIndex] = submenu;
} else {
// Add new submenu
menuDict[mainMenuId].entries.push(submenu);
}
}
// Handle main menu payload
else {
const menuId = menu.id;
// Preserve existing entries if new payload doesn't include them
const existingentries = menuDict[menuId]?.entries || [];
menuDict[menuId] = {
position: menu.position,
id: menu.id,
name: menu.name,
text: menu.text,
icon: menu.icon,
description: menu.description,
entries: menu.entries || existingentries
};
}
}
return menuDict;
}
async function injectLogoTheme(menuJson, logoPath, themePath) {
if (!menuJson.fields || !menuJson.fields.config) {
console.warn("⚠️ menuJson is missing 'fields.config'");
return;
}
// Parse the existing config JSON string
let config;
try {
config = JSON.parse(menuJson.fields.config);
} catch (e) {
console.error("❌ Failed to parse menuJson.fields.config:", e);
return;
}
// Inject logo
if (logoPath && fs.existsSync(logoPath)) {
const img = fs.readFileSync(logoPath);
const mimeType = mime.lookup(logoPath) || 'image/png';
const base64 = img.toString('base64');
config.logo = {
value: `data:${mimeType};base64,${base64}`
};
}
// Inject theme
if (themePath && fs.existsSync(themePath)) {
const themeData = JSON.parse(fs.readFileSync(themePath, 'utf8'));
config.theme = themeData.theme;
}
// Write back to config as string
menuJson.fields.config = JSON.stringify(config, null, 2);
}
// Function to get headers with GitHub API key
function getHeaders() {
const headers = {
'Accept': 'application/vnd.github.v3+json'
};
if (sourceType === 'github' && githubAuthType === 'authenticated' && githubApiKey) {
headers['Authorization'] = `Bearer ${githubApiKey}`;
}
return headers;
}
function generateDeterministicUUID(inputString) {
// Initialize seed for deterministic random
let seed = 0;
for (let i = 0; i < inputString.length; i++) {
seed += inputString.charCodeAt(i);
}
// Simple pseudo-random number generator based on seed
function seededRandom() {
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280;
}
// UUID template: 8-4-4-4-12 characters
const chars = '0123456789abcdef';
let uuid = '';
// Generate UUID parts
for (let i = 0; i < 36; i++) {
if (i === 8 || i === 13 || i === 18 || i === 23) {
uuid += '-';
} else {
uuid += chars[Math.floor(seededRandom() * 16)];
}
}
return uuid;
}
function transformRolesToFixture(rolesDict) {
const roleFixtures = [];
const roleRightFixtures = [];
const validityFrom = "2025-01-01T00:00:00Z";
for (const key in rolesDict) {
const role = rolesDict[key];
const roleUuid = generateDeterministicUUID(key);
roleFixtures.push({
model: "core.role",
fields: {
uuid: roleUuid,
name: role.roleName,
alt_language: null,
is_system: 0,
is_blocked: false,
audit_user_id: null,
validity_from: validityFrom,
validity_to: null,
legacy_id: null
}
});
for (const perm of role.permissions) {
roleRightFixtures.push({
model: "core.roleright",
fields: {
validity_from: validityFrom,
validity_to: null,
legacy_id: null,
right_id: perm.code,
audit_user_id: null,
role: [role.roleName]
}
});
}
}
return {
roles: roleFixtures,
rolesRight: roleRightFixtures
};
}
async function createSolutionDirectory(baseDir, output)
{
try {
// Ensure the base directory exists
await fs.mkdirSync(baseDir, { recursive: true });
// Iterate over the output object
for (const [filePath, content] of Object.entries(output)) {
// Resolve the full path for the file
const fullPath = path.join(baseDir, filePath);
// Ensure the directory for the file exists
const dir = path.dirname(fullPath);
await fs.mkdirSync(dir, { recursive: true });
// Write the file content
if (fullPath.toLowerCase().endsWith('.yml') || fullPath.toLowerCase().endsWith('.yaml')) {
// Stringify as YAML
await fs.writeFileSync(fullPath, yaml.dump(content));
} else if (fullPath.toLowerCase().endsWith('.json') ){
// Stringify as JSON with formatting
await fs.writeFileSync(fullPath, JSON.stringify(content, null, 2));
} else {
// Stringify as JSON with formatting
await fs.writeFileSync(fullPath, content);
}
}
console.log(`Directory and files created successfully in ${baseDir}`);
} catch (error) {
console.error('Error creating directory and files:', error);
throw error;
}
}
// Function to create a zip file
async function createZip(data, filename) {
const zip = new JSZip();
Object.entries(data).forEach(([name, content]) => {
// Check if the filename ends with .yml or .yaml (case-insensitive)
if (name.toLowerCase().endsWith('.yml') || name.toLowerCase().endsWith('.yaml')) {
// Stringify as YAML
zip.file(name, yaml.dump(content));
} else {
// Stringify as JSON with formatting
zip.file(name, JSON.stringify(content, null, 2));
}
});
try {
const content = await zip.generateAsync({ type: "blob" });
if (typeof window === 'undefined') {
// Node.js: Convert Blob to Buffer and write to disk
const buffer = Buffer.from(await content.arrayBuffer());
fs.writeFileSync(filename, buffer);
console.log(`ZIP file "${filename}" created successfully on disk!`);
} else {
// Browser: Trigger download
const link = document.createElement("a");
link.href = URL.createObjectURL(content);
link.download = filename;
link.click();
console.log(`ZIP file "${filename}" triggered for download!`);
}
} catch (error) {
console.error("Error creating ZIP file:", error);
}
}
module.exports = { mergeSolutions, getAbsolutePath, createZip, processSolutions, createSolutionDirectory };