-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcodeInjector.ts
More file actions
1240 lines (1073 loc) · 47.7 KB
/
codeInjector.ts
File metadata and controls
1240 lines (1073 loc) · 47.7 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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { exec, spawn } from 'child_process';
import filewatcher from 'filewatcher'; // todo - replace this legacy (>8y old module) with chokidar
import fs from 'fs';
import fsExtra from 'fs-extra';
import os from 'os';
import path from 'path';
import { promisify } from 'util';
import yaml from 'yaml';
import AdminForth, { AdminForthConfigMenuItem } from '../index.js';
import { ADMIN_FORTH_ABSOLUTE_PATH, getComponentNameFromPath, transformObject, deepMerge, md5hash, slugifyString } from './utils.js';
import { ICodeInjector } from '../types/Back.js';
import { StylesGenerator } from './styleGenerator.js';
import { afLogger } from '../modules/logger.js';
import { pathToFileURL } from 'url';
let TMP_DIR;
try {
TMP_DIR = os.tmpdir();
} catch (e) {
if (process.platform === 'win32') {
TMP_DIR = process.env.TEMP || process.env.TMP || 'C:\\Windows\\Temp';
} else {
TMP_DIR = '/tmp';
}//maybe we can consider to use node_modules/.cache/adminforth here instead of tmp
}
function stripAnsiCodes(str) {
// Regular expression to match ANSI escape codes
return str.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '');
}
function findHomePage(menuItem: AdminForthConfigMenuItem[]): AdminForthConfigMenuItem | undefined {
for (const item of menuItem) {
if (item.homepage) {
return item;
}
if (item.children) {
const found = findHomePage(item.children);
if (found) {
return found;
}
}
}
return undefined;
}
async function findFirstMenuItemWithResource(menuItem: AdminForthConfigMenuItem[]): Promise<AdminForthConfigMenuItem | undefined> {
for (const item of menuItem) {
if (item.path || item.resourceId) {
return item;
}
if (item.children) {
const found = await findFirstMenuItemWithResource(item.children);
if (found) {
return found;
}
}
}
return undefined;
}
const execAsync = promisify(exec);
function hashify(obj) {
return md5hash(JSON.stringify(obj));
}
function isFulfilled<T>(result: PromiseSettledResult<T>): result is PromiseFulfilledResult<T> {
return result.status === 'fulfilled';
}
function notifyWatcherIssue(limit) {
console.log('Ran out of file handles after watching %s files.', limit);
console.log('Falling back to polling which uses more CPU.');
console.log('Run ulimit -n 10000 to increase the limit for open files.');
}
class CodeInjector implements ICodeInjector {
allWatchers = [];
adminforth: AdminForth;
allComponentNames: { [key: string]: string } = {};
srcFoldersToSync: { [key: string]: string } = {};
publicFoldersToSync: { [key: string]: string } = {};
devServerPort: number = null;
spaTmpPath(): string {
const brandSlug = this.adminforth.config.customization.brandNameSlug
if (!brandSlug) {
throw new Error('brandSlug is empty, but it should be populated at least by config Validator ');
}
return path.join(TMP_DIR, 'adminforth', brandSlug, 'spa_tmp');
}
async checkIconNames(icons: string[]) {
process.env.HEAVY_DEBUG && console.log(`Checking icon names: ${icons.join(', ')}`);
const uniqueIcons = Array.from(new Set(icons));
process.env.HEAVY_DEBUG && console.log(`Unique icons: ${uniqueIcons.join(', ')}`);
const collections = new Set(icons.map((icon) => icon.split(':')[0]));
process.env.HEAVY_DEBUG && console.log(`Icon collections: ${Array.from(collections).join(', ')}`);
const iconPackageNames = Array.from(collections).map((collection) => `@iconify-prerendered/vue-${collection}`);
process.env.HEAVY_DEBUG && console.log(`Icon package names: ${iconPackageNames.join(', ')}`);
const iconPackages = (
await Promise.allSettled(
iconPackageNames.map(
async (pkg) => (
{
pkg: await import(pathToFileURL(path.join(this.spaTmpPath(), 'node_modules', pkg, 'index.js')).href),
name: pkg
}
)
)
)
);
process.env.HEAVY_DEBUG && console.log(`Icon packages load results: ${iconPackages.map(res => res.status === 'fulfilled' ? res.value.name : 'error:' + res.reason).join(', ')}`);
const loadedIconPackages = iconPackages.filter(isFulfilled).map((res) => res.value).reduce((acc, { pkg, name }) => {
acc[name.slice(`@iconify-prerendered/vue-`.length)] = pkg;
return acc;
}, {});
process.env.HEAVY_DEBUG && console.log(`Loaded icon packages: ${Object.keys(loadedIconPackages).join(', ')}`);
uniqueIcons.forEach((icon) => {
const [ collection, iconName ] = icon.split(':');
const PascalIconName = 'Icon' + iconName.split('-').map((part, index) => {
return part[0].toUpperCase() + part.slice(1);
}).join('');
process.env.HEAVY_DEBUG && console.log(`Checking icon: ${icon}, collection: ${collection}, iconName: ${iconName}, PascalIconName: ${PascalIconName}`);
if (!loadedIconPackages[collection]) {
throw new Error(`Collection ${collection} not found`);
}
if (!loadedIconPackages[collection][PascalIconName]) {
throw new Error(`Icon ${iconName} not found in collection ${collection}`);
}
});
}
registerCustomComponent(filePath: string): void {
const componentName = getComponentNameFromPath(filePath);
this.allComponentNames[filePath] = componentName;
}
cleanup() {
console.log('Cleaning up...');
this.allWatchers.forEach((watcher) => {
watcher.removeAll();
});
}
constructor(adminforth) {
this.adminforth = adminforth;
['SIGINT', 'SIGTERM', 'SIGQUIT']
.forEach(signal => process.on(signal, () => {
this.cleanup();
process.exit();
}));
}
async doesUserHasPnpmLockFile(dir: string): Promise<boolean> {
if (!dir) {
return false;
}
const usersPackagePath = path.join(dir, 'package.json');
let packageContent: { dependencies: any, devDependencies: any } = null;
try {
packageContent = JSON.parse(await fs.promises.readFile(usersPackagePath, 'utf-8'));
} catch (e) {
// user package.json does not exist, user does not have custom components
}
if (packageContent) {
const lockPath = path.join(dir, 'pnpm-lock.yaml');
let lock: any = null;
try {
lock = yaml.parse(await fs.promises.readFile(lockPath, 'utf-8'));
return true;
} catch (e) {
return false;
}
}
return false;
}
async runPackageManagerShell({command, cwd, envOverrides = {}}: {
command: string,
cwd: string,
envOverrides?: { [key: string]: string }
}) {
const nodeBinary = process.execPath; // Path to the Node.js binary running this script
const doesUserHavePnpmLock = await this.doesUserHasPnpmLockFile(this.adminforth.config.customization.customComponentsDir);
// On Windows, npm/pnpm is npm/pnpm.cmd, on Unix systems it's npm/pnpm
let packageExecutable
if (doesUserHavePnpmLock) {
process.env.HEAVY_DEBUG && console.log(`User has pnpm-lock.yaml, using pnpm for installing custom components`);
packageExecutable = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
} else {
process.env.HEAVY_DEBUG && console.log(`User does not have pnpm-lock.yaml, falling back to npm for installing custom components`);
packageExecutable = process.platform === 'win32' ? 'npm.cmd' : 'npm';
}
const packagePath = path.join(path.dirname(nodeBinary), packageExecutable); // Path to the package executable
const env = {
VITE_ADMINFORTH_PUBLIC_PATH: this.adminforth.config.baseUrl,
FORCE_COLOR: '1',
...process.env,
...envOverrides,
};
process.env.HEAVY_DEBUG && console.log(`⚙️ exec: ${packageExecutable} ${command}`);
process.env.HEAVY_DEBUG && console.log(`🪲 ${packageExecutable} ${command} cwd: ${cwd}`);
let execCommand: string;
if (process.platform === 'win32') {
// Quote path if it contains spaces
const quotedPackagePath = packagePath.includes(' ') ? `"${packagePath}"` : packagePath;
execCommand = `${quotedPackagePath} ${command}`;
} else {
// Quote paths that contain spaces (for Unix systems)
const quotedNodeBinary = nodeBinary.includes(' ') ? `"${nodeBinary}"` : nodeBinary;
const quotedPackagePath = packagePath.includes(' ') ? `"${packagePath}"` : packagePath;
execCommand = `${quotedNodeBinary} ${quotedPackagePath} ${command}`;
}
const execOptions: any = {
cwd,
env,
};
if (process.platform === 'win32') {
execOptions.shell = true;
}
const { stderr: err } = await execAsync(execCommand, execOptions);
process.env.HEAVY_DEBUG && console.log(`${packageExecutable} ${command} done in`);
if (err) {
process.env.HEAVY_DEBUG && console.log(`🪲${packageExecutable} ${command} errors/warnings: ${err}`);
}
}
async rmTmpDir() {
// remove spa_tmp folder if it is exists
try {
await fs.promises.rm(
this.spaTmpPath(), { recursive: true });
} catch (e) {
// ignore
}
}
getServeDir() {
return path.join(this.getSpaDir(), 'dist');
}
async packagesFromPnpm(dir: string): Promise<[string, string[]]> {
const usersPackagePath = path.join(dir, 'package.json');
let packageContent: { dependencies: any, devDependencies: any } = null;
let lockHash: string = '';
let packages: string[] = [];
try {
packageContent = JSON.parse(await fs.promises.readFile(usersPackagePath, 'utf-8'));
} catch (e) {
// user package.json does not exist, user does not have custom components
}
if (packageContent) {
const lockPath = path.join(dir, 'pnpm-lock.yaml');
let lock: any = null;
try {
lock = yaml.parse(await fs.promises.readFile(lockPath, 'utf-8'));
} catch (e) {
const npmLockPath = path.join(dir, 'package-lock.json');
let npmLock: any = null;
try {
npmLock = JSON.parse(await fs.promises.readFile(npmLockPath, 'utf-8'));
} catch (npmLockError) {
throw new Error(`Custom pnpm-lock.yaml or package-lock.json does not exist in ${dir}, but package.json does.
We can't determine version of packages without pnpm-lock.yaml or package-lock.json. Please run pnpm install or npm install in ${dir}`);
}
lockHash = hashify(npmLock);
packages = [
...Object.keys(packageContent.dependencies || {}),
...Object.keys(packageContent.devDependencies || {})
].reduce(
(acc, packageName) => {
const pack = npmLock?.packages?.[`node_modules/${packageName}`];
if (!pack?.version) {
throw new Error(`Package ${packageName} is not in package-lock.json but is in package.json. Please run 'npm install' in ${dir}`);
}
acc.push(`${packageName}@${pack.version}`);
return acc;
}, []
);
return [lockHash, packages];
}
lockHash = hashify(lock);
const importer = lock?.importers?.['.'];
if (!importer) {
throw new Error(`pnpm-lock.yaml in ${dir} does not contain importer ".". Please run pnpm install in ${dir}`);
}
const importerDeps = {
...(importer.dependencies || {}),
...(importer.devDependencies || {}),
...(importer.optionalDependencies || {}),
};
packages = [
...Object.keys(packageContent.dependencies || {}),
...Object.keys(packageContent.devDependencies || {})
].reduce(
(acc, packageName) => {
const depInfo = importerDeps[packageName];
const raw = typeof depInfo === 'string'
? depInfo
: (depInfo?.version || depInfo?.specifier);
if (!raw) {
throw new Error(`Package ${packageName} is not in pnpm-lock.yaml but is in package.json. Please run 'pnpm install' in ${dir}`);
}
const cleaned = raw.includes('(') ? raw.split('(')[0] : raw;
acc.push(`${packageName}@${cleaned}`);
return acc;
}, []
);
}
return [lockHash, packages];
}
getSpaDir() {
let spaDir = path.join(ADMIN_FORTH_ABSOLUTE_PATH, 'spa');
if (!fs.existsSync(spaDir)) {
spaDir = path.join(ADMIN_FORTH_ABSOLUTE_PATH, 'dist', 'spa');
}
return spaDir;
}
registerPluginPublicFoldersToSync() {
this.publicFoldersToSync = {};
for (const plugin of this.adminforth.activatedPlugins) {
const pluginPublicFolderPath = path.join(plugin.customFolderPath, 'public');
if (fs.existsSync(pluginPublicFolderPath)) {
this.publicFoldersToSync[pluginPublicFolderPath] = `./plugins/${plugin.className}/`;
}
}
}
async updatePartials({ filesUpdated }: { filesUpdated: string[] }) {
const spaDir = this.getSpaDir();
// copy only updated files
await Promise.all(filesUpdated.map(async (file) => {
const src = path.join(spaDir, file);
const dest = path.join(this.spaTmpPath(), file);
// overwrite:true can't be used to not destroy cache
await fsExtra.copy(src, dest, {
dereference: true, // needed to dereference types
// preserveTimestamps: true, // needed to not invalidate any caches
});
process.env.HEAVY_DEBUG && console.log(`🪲⚙️ fsExtra.copy copy single file, ${src}, ${dest}`);
}));
}
async migrateLegacyCustomLayout(oldMeta) {
if (oldMeta.customLayout === true) {
oldMeta.sidebarAndHeader = "none";
}
return oldMeta;
}
async prepareSources() {
// collects all files and folders into SPA_TMP_DIR
// check spa tmp folder exists and create if not
try {
await fs.promises.access(this.spaTmpPath(), fs.constants.F_OK);
} catch (e) {
await fs.promises.mkdir(this.spaTmpPath(), { recursive: true });
}
const icons = [];
let routes = '';
let routerComponents = '';
const collectAssetsFromMenu = (menu) => {
menu.forEach((item) => {
if (item.icon) {
icons.push(item.icon);
}
if (item.component) {
if(Object.keys(item).includes('isStaticRoute')) {
if(!item.isStaticRoute) {
routes += `{
path: '${item.path}',
name: '${item.path}',
component: () => import('${item.component}'),
meta: { title: '${item?.meta?.title || item?.label || item.path.replace('/', '')}'}
},\n`
} else {
routes += `{
path: '${item.path}',
name: '${item.path}',
component: ${getComponentNameFromPath(item.component)},
meta: { title: '${item?.meta?.title || item?.label ||item.path.replace('/', '')}'}
},\n`
const componentName = `${getComponentNameFromPath(item.component)}`;
routerComponents += `import ${componentName} from '${item.component}';\n`;
}
} else {
if (item.homepage) {
routes += `{
path: '${item.path}',
name: '${item.path}',
component: ${getComponentNameFromPath(item.component)},
meta: { title: '${item?.meta?.title || item?.label || item.path.replace('/', '')}'}
},\n`
const componentName = `${getComponentNameFromPath(item.component)}`;
routerComponents += `import ${componentName} from '${item.component}';\n`;
} else {
routes += `{
path: '${item.path}',
name: '${item.path}',
component: () => import('${item.component}'),
meta: { title: '${item?.meta?.title || item.path.replace('/', '')}'}
},\n`
}
}
}
if (item.children) {
collectAssetsFromMenu(item.children);
}
});
};
const registerCustomPages = (config) => {
if (config.customization.customPages) {
config.customization.customPages.forEach(async (page) => {
const newMeta = await this.migrateLegacyCustomLayout(page?.component?.meta || {});
routes += `{
path: '${page.path}',
name: '${page.path}',
component: () => import('${page?.component?.file || page.component}'),
meta: ${
JSON.stringify({
...newMeta,
title: page.meta?.title || page.path.replace('/', '')
})
}
},`})
}}
const registerSettingPages = ( settingPage ) => {
if (!settingPage) {
return;
}
for (const page of settingPage) {
if (page.icon) {
icons.push(page.icon);
}
}
}
registerCustomPages(this.adminforth.config);
collectAssetsFromMenu(this.adminforth.config.menu);
registerSettingPages(this.adminforth.config.auth.userMenuSettingsPages);
const spaDir = this.getSpaDir();
process.env.HEAVY_DEBUG && console.log(`🪲⚙️ fsExtra.copy from ${spaDir} -> ${this.spaTmpPath()}`);
// try to rm <spa tmp path>/src/types directory
try {
await fs.promises.rm(path.join(this.spaTmpPath(), 'src', 'types'), { recursive: true });
} catch (e) {
// ignore
}
// overwrite can't be used to not destroy cache
await fsExtra.copy(spaDir, this.spaTmpPath(), {
filter: (src) => {
// /adminforth/* used for local development and /dist/* used for production
const filterPasses = !src.includes(`${path.sep}adminforth${path.sep}spa${path.sep}node_modules`) && !src.includes(`${path.sep}adminforth${path.sep}spa${path.sep}dist`)
&& !src.includes(`${path.sep}dist${path.sep}spa${path.sep}node_modules`) && !src.includes(`${path.sep}dist${path.sep}spa${path.sep}dist`);
if (!filterPasses) {
process.env.HEAVY_DEBUG && console.log(`🪲⚙️ fsExtra.copy filtered out, ${src}`);
}
return filterPasses
},
dereference: true, // needed to dereference types
});
// copy whole custom directory
if (this.adminforth.config.customization?.customComponentsDir) {
// resolve customComponentsDir to absolute path, so ./aa will be resolved to /path/to/current/dir/aa
const customCompAbsPath = path.resolve(this.adminforth.config.customization.customComponentsDir);
this.srcFoldersToSync[customCompAbsPath] = './'
}
this.registerPluginPublicFoldersToSync();
// if this.adminforth.config.customization.favicon is set, copy it to assets
const customFav = this.adminforth.config.customization?.favicon;
if (customFav) {
const faviconPath = path.join(this.adminforth.config.customization?.customComponentsDir, customFav.replace('@@/', ''));
const dest = path.join(this.spaTmpPath(), 'public', 'assets', customFav.replace('@@/', ''));
// make sure all folders in dest exist
await fsExtra.ensureDir(path.dirname(dest));
await fsExtra.copy(faviconPath, dest);
}
for (const [src, dest] of Object.entries(this.srcFoldersToSync)) {
const to = path.join(this.spaTmpPath(), 'src', 'custom', dest);
process.env.HEAVY_DEBUG && console.log(`🪲⚙️ srcFoldersToSync: fsExtra.copy from ${src}, ${to}`);
await fsExtra.copy(src, to, {
recursive: true,
dereference: true,
// exclude if node_modules comes after /custom/ in path
filter: (src) => !src.includes(path.join('custom', 'node_modules')),
});
}
for (const [src, dest] of Object.entries(this.publicFoldersToSync)) {
const to = path.join(this.spaTmpPath(), 'public', dest);
process.env.HEAVY_DEBUG && console.log(`🪲⚙️ publicFoldersToSync: fsExtra.copy from ${src}, ${to}`);
await fsExtra.copy(src, to, {
recursive: true,
dereference: true,
});
}
//collect all 'icon' fields from resources bulkActions
this.adminforth.config.resources.forEach((resource) => {
if (resource.options?.bulkActions) {
resource.options.bulkActions.forEach((action) => {
if (action.icon) {
icons.push(action.icon);
}
});
}
if (resource.options?.actions) {
resource.options.actions.forEach((action) => {
if (action.icon) {
icons.push(action.icon);
}
});
}
});
const uniqueIcons = Array.from(new Set(icons));
// icons are collectionName:iconName. Get list of all unique collection names:
const collections = new Set(icons.map((icon) => icon.split(':')[0]));
// package names @iconify-prerendered/vue-<collection name>
const iconPackageNames = Array.from(collections).map((collection) => `@iconify-prerendered/vue-${collection}`);
// for each icon generate import statement
const iconImports = uniqueIcons.map((icon) => {
const [ collection, iconName ] = icon.split(':');
const PascalIconName = 'Icon' + iconName.split('-').map((part, index) => {
return part[0].toUpperCase() + part.slice(1);
}).join('');
return `import { ${PascalIconName} } from '@iconify-prerendered/vue-${collection}';`;
}).join('\n');
// for each custom component generate import statement
const customResourceComponents = [];
function checkInjections(filePathes) {
filePathes.forEach(({ file }) => {
if (!customResourceComponents.includes(file)) {
if (file === undefined) {
throw new Error('file is undefined');
}
customResourceComponents.push(file);
}
});
}
this.adminforth.config.resources.forEach((resource) => {
resource.columns.forEach((column) => {
if (column.components) {
Object.values(column.components).forEach(({ file }: {file: string}) => {
if (!customResourceComponents.includes(file)) {
if (file === undefined) {
throw new Error('file is undefined from field.components, field:' + JSON.stringify(column));
}
customResourceComponents.push(file);
}
});
}
});
resource.options.actions.forEach((action) => {
const cc = action.customComponent;
if (!cc) return;
const file = (typeof cc === 'string') ? cc : cc.file;
if (!file) {
throw new Error('customComponent.file is missing for action: ' + JSON.stringify({ id: action.id, name: action.name }));
}
if (!customResourceComponents.includes(file)) {
customResourceComponents.push(file);
}
});
(Object.values(resource.options?.pageInjections || {})).forEach((injection) => {
Object.values(injection).forEach((filePathes: {file: string}[]) => {
checkInjections(filePathes);
});
});
});
if (this.adminforth.config.customization?.globalInjections) {
Object.values(this.adminforth.config.customization.globalInjections).forEach((injection) => {
checkInjections(injection);
});
}
if (this.adminforth.config.customization?.loginPageInjections) {
Object.values(this.adminforth.config.customization.loginPageInjections).forEach((injection) => {
checkInjections(injection);
});
}
if (this.adminforth.config.auth.userMenuSettingsPages) {
for (const settingPage of this.adminforth.config.auth.userMenuSettingsPages) {
checkInjections([{ file: settingPage.component }]);
}
}
if (this.adminforth.config.componentsToExplicitRegister) {
this.adminforth.config.componentsToExplicitRegister.forEach((component) => {
if (!customResourceComponents.includes(component)) {
customResourceComponents.push(component.file);
}
});
}
customResourceComponents.forEach((filePath) => {
const componentName = getComponentNameFromPath(filePath);
this.allComponentNames[filePath] = componentName;
});
let customComponentsImports = '';
for (const [targetPath, component] of Object.entries(this.allComponentNames)) {
customComponentsImports += `import ${component} from '${targetPath}';\n`;
}
// Generate Vue.component statements for each icon
const iconComponents = uniqueIcons.map((icon) => {
const [ collection, iconName ] = icon.split(':');
const PascalIconName = 'Icon' + iconName.split('-').map((part, index) => {
return part[0].toUpperCase() + part.slice(1);
}).join('');
return `app.component('${PascalIconName}', ${PascalIconName});`;
}).join('\n');
// Generate Vue.component statements for each custom component
let customComponentsComponents = '';
for (const name of Object.values(this.allComponentNames)) {
customComponentsComponents += `app.component('${name}', ${name});\n`;
}
let imports = iconImports + '\n';
imports += customComponentsImports + '\n';
if (this.adminforth.config.customization?.vueUsesFile) {
imports += `import addCustomUses from '${this.adminforth.config.customization.vueUsesFile}';\n`;
}
// inject that code into spa_tmp/src/App.vue
const appVuePath = path.join(this.spaTmpPath(), 'src', 'main.ts');
let appVueContent = await fs.promises.readFile(appVuePath, 'utf-8');
appVueContent = appVueContent.replace('/* IMPORTANT:ADMINFORTH IMPORTS */', imports);
appVueContent = appVueContent.replace('/* IMPORTANT:ADMINFORTH COMPONENT REGISTRATIONS */', iconComponents + '\n' + customComponentsComponents + '\n');
if (this.adminforth.config.customization?.vueUsesFile) {
appVueContent = appVueContent.replace('/* IMPORTANT:ADMINFORTH CUSTOM USES */', 'addCustomUses(app);');
}
await fs.promises.writeFile(appVuePath, appVueContent);
// generate tailwind extend styles
const stylesGenerator = new StylesGenerator(this.adminforth.config.customization?.styles);
const stylesText = JSON.stringify(stylesGenerator.mergeStyles(), null, 2).slice(1, -1);
let tailwindConfigPath = path.join(this.spaTmpPath(), 'tailwind.config.js');
let tailwindConfigContent = await fs.promises.readFile(tailwindConfigPath, 'utf-8');
tailwindConfigContent = tailwindConfigContent.replace('/* IMPORTANT:ADMINFORTH TAILWIND STYLES */', stylesText);
await fs.promises.writeFile(tailwindConfigPath, tailwindConfigContent);
const routerVuePath = path.join(this.spaTmpPath(), 'src', 'router', 'index.ts');
let routerVueContent = await fs.promises.readFile(routerVuePath, 'utf-8');
routerVueContent = routerVueContent.replace('/* IMPORTANT:ADMINFORTH ROUTES IMPORTS */', routerComponents);
// inject title to index.html
const indexHtmlPath = path.join(this.spaTmpPath(), 'index.html');
let indexHtmlContent = await fs.promises.readFile(indexHtmlPath, 'utf-8');
indexHtmlContent = indexHtmlContent.replace('/* IMPORTANT:ADMINFORTH TITLE */', `${this.adminforth.config.customization?.title || this.adminforth.config.customization?.brandName || 'AdminForth'}`);
// we dont't need to add baseUrl in front of assets here, because it is already added by Vite/Vue
indexHtmlContent = indexHtmlContent.replace(
'/* IMPORTANT:ADMINFORTH FAVICON */',
this.adminforth.config.customization.favicon?.replace('@@/', `/assets/`)
||
`/assets/favicon.png`
);
// inject heads to index.html
const headItems = this.adminforth.config.customization?.customHeadItems;
if(headItems){
const renderedHead = headItems.map(({ tagName, attributes, innerCode }) => {
const attrs = Object.entries(attributes)
.map(([key, value]) => `${key}="${value}"`)
.join(' ');
const isVoid = ['base', 'link', 'meta'].includes(tagName);
return isVoid
? `<${tagName} ${attrs}>`
: `<${tagName} ${attrs}> ${innerCode} </${tagName}>`;
}).join('\n ');
indexHtmlContent = indexHtmlContent.replace(" <!-- /* IMPORTANT:ADMINFORTH HEAD */ -->", `${renderedHead}` );
}
await fs.promises.writeFile(indexHtmlPath, indexHtmlContent);
/* generate custom routes */
let homepageMenuItem: AdminForthConfigMenuItem = findHomePage(this.adminforth.config.menu);
if (!homepageMenuItem) {
// find first item with path or resourceId. If we face a menu item with children earlier then path/resourceId, we should search in children
homepageMenuItem = await findFirstMenuItemWithResource(this.adminforth.config.menu);
}
if (!homepageMenuItem) {
throw new Error('No homepage found in menu and no menu item with path/resourceId found. AdminForth can not generate routes');
}
let homePagePath = homepageMenuItem.path || `/resource/${homepageMenuItem.resourceId}`;
if (!homePagePath) {
homePagePath=this.adminforth.config.menu.filter((mi)=>mi.path)[0]?.path || `/resource/${this.adminforth.config.menu.filter((mi)=>mi.children)[0]?.resourceId}` ;
}
routes += `{
path: '/',
name: 'home',
//redirect to login
redirect: '${homePagePath}'
},\n`;
routerVueContent = routerVueContent.replace('/* IMPORTANT:ADMINFORTH ROUTES */', routes);
await fs.promises.writeFile(routerVuePath, routerVueContent);
/* hash checking */
let spaLockHash = '';
if (await this.doesUserHasPnpmLockFile(this.adminforth.config.customization.customComponentsDir)) {
const spaPnpmLockPath = path.join(this.spaTmpPath(), 'pnpm-lock.yaml');
const spaPnpmLock = yaml.parse(await fs.promises.readFile(spaPnpmLockPath, 'utf-8'));
spaLockHash = hashify(spaPnpmLock);
} else {
const spaNpmLockPath = path.join(this.spaTmpPath(), 'package-lock.json');
const spaNpmLock = JSON.parse(await fs.promises.readFile(spaNpmLockPath, 'utf-8'));
spaLockHash = hashify(spaNpmLock);
}
/* customPackageLock */
let usersLockHash: string = '';
let usersPackages: string[] = [];
if (this.adminforth.config.customization?.customComponentsDir) {
[usersLockHash, usersPackages] = await this.packagesFromPnpm(this.adminforth.config.customization.customComponentsDir);
}
const pluginPackages: {
pluginName: string,
lockHash: string,
packages: string[],
}[] = [];
// for every installed plugin generate packages
for (const plugin of this.adminforth.activatedPlugins) {
process.env.HEAVY_DEBUG && console.log(`🔧 Checking packages for plugin, ${plugin.constructor.name}, ${plugin.customFolderPath}`);
const [lockHash, packages] = await this.packagesFromPnpm(plugin.customFolderPath);
if (packages.length) {
pluginPackages.push({
pluginName: plugin.constructor.name,
lockHash,
packages,
});
}
}
// form string "pluginName:lockHash::pLugin2Name:lockHash"
const pluginsLockHash = pluginPackages.map(({ pluginName, lockHash }) => `${pluginName}>${lockHash}`).join('::');
const iconPackagesNamesHash = hashify(iconPackageNames);
const fullHash = `spa>${spaLockHash}::icons>${iconPackagesNamesHash}::user/custom>${usersLockHash}::${pluginsLockHash}`;
const hashPath = path.join(this.spaTmpPath(), 'node_modules', '.adminforth_hash');
try {
const existingHash = await fs.promises.readFile(hashPath, 'utf-8');
await this.checkIconNames(icons);
if (existingHash === fullHash) {
process.env.HEAVY_DEBUG && console.log(`🪲Hashes match, skipping pnpm install, from file: ${existingHash}, actual: ${fullHash}`);
return;
} else {
process.env.HEAVY_DEBUG && console.log(`🪲 Hashes do not match: from file: ${existingHash} actual: ${fullHash}, proceeding with pnpm install`);
}
} catch (e) {
// ignore
process.env.HEAVY_DEBUG && console.log(`🪲Hash file does not exist, proceeding with pnpm install, ${e}`);
}
// install --frozen-lockfile works for npm and pnpm
await this.runPackageManagerShell({command: 'install --frozen-lockfile', cwd: this.spaTmpPath(), envOverrides: {
NODE_ENV: 'development' // otherwise it will not install devDependencies which we still need, e.g for extract
}});
const allPacks = [
...iconPackageNames,
...usersPackages,
...pluginPackages.reduce((acc, { packages }) => {
acc.push(...packages);
return acc;
}, []),
];
const EXCLUDE_PACKS = ['@iconify-prerendered/vue-flowbite'];
const allPacksFiltered = allPacks.filter((pack) => {
return !EXCLUDE_PACKS.some((exclude) => pack.startsWith(exclude));
})
const allPacksUnique = Array.from(new Set(allPacksFiltered));
if (allPacks.length) {
const packageManagerInstallCommand = `install ${allPacksUnique.join(' ')}`;
await this.runPackageManagerShell({
command: packageManagerInstallCommand, cwd: this.spaTmpPath(),
envOverrides: {
NODE_ENV: 'development' // otherwise it will not install devDependencies which we still need, e.g for extract
}
});
}
await this.checkIconNames(icons);
await fs.promises.writeFile(hashPath, fullHash);
}
async watchForReprepare({}) {
const spaPath = this.getSpaDir();
// get list of all subdirectories in spa recursively (for SPA development)
const directories = [];
const collectDirectories = async (dir) => {
const files = await fs.promises.readdir(dir, { withFileTypes: true });
for (const file of files) {
if (['node_modules', 'dist'].includes(file.name)) {
continue;
}
if (file.isDirectory()) {
directories.push(path.join(dir, file.name));
await collectDirectories(path.join(dir, file.name));
}
}
};
await collectDirectories(spaPath);
process.env.HEAVY_DEBUG && console.log(`🪲🔎 Watch for: ${directories.join(',')}`);
const watcher = filewatcher({ debounce: 30 });
directories.forEach((dir) => {
// read directory files and add to watcher, only files not directories
const files = fs.readdirSync(dir);
files.forEach((file) => {
const fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isFile()) {
process.env.HEAVY_DEBUG && console.log(`🪲🔎 Watch for file ${fullPath}`);
watcher.add(fullPath);
}
})
});
watcher.on(
'change',
async (file) => {
process.env.HEAVY_DEBUG && console.log(`🐛 File ${file} changed (SPA), preparing sources...`);
await this.updatePartials({ filesUpdated: [file.replace(spaPath + path.sep, '')] });
}
)
watcher.on('fallback', notifyWatcherIssue);
this.allWatchers.push(watcher);
}
async watchCustomComponentsForCopy({ customComponentsDir, destination, targetRoot = path.join('src', 'custom') }: {
customComponentsDir: string,
destination: string,
targetRoot?: string,
}) {
if (!customComponentsDir) {
return;
}
// check if folder exists
try {
await fs.promises.access(customComponentsDir, fs.constants.F_OK);
} catch (e) {
process.env.HEAVY_DEBUG && console.log(`🪲Custom components dir ${customComponentsDir} does not exist, skipping watching`);
return;
}
// get all subdirs
const directories = [];
const files = []
const collectDirectories = async (dir) => {
if (['node_modules', 'dist'].includes(path.basename(dir))) {
return;
}
directories.push(dir);
const filesAndDirs = await fs.promises.readdir(dir, { withFileTypes: true });
await Promise.all(
filesAndDirs.map(
async (file) => {
const isDir = fs.lstatSync(path.join(dir, file.name)).isDirectory();
if (isDir) {
await collectDirectories(path.join(dir, file.name));
} else {
files.push(path.join(dir, file.name));
}
}
)
)
};
await collectDirectories(customComponentsDir);
const watcher = filewatcher({ debounce: 30 });
files.forEach((file) => {
process.env.HEAVY_DEBUG && console.log(`🪲🔎 Watch for file ${file}`);
watcher.add(file);
});
process.env.HEAVY_DEBUG && console.log(`🪲🔎 Watch for: ${directories.join(',')}`);
watcher.on(
'change',
async (fileOrDir) => {
// copy one file
const relativeFilename = fileOrDir.replace(customComponentsDir + path.sep, '');
process.env.HEAVY_DEBUG && console.log(`🔎 fileOrDir ${fileOrDir} changed`);
process.env.HEAVY_DEBUG && console.log(`🔎 relativeFilename ${relativeFilename}`);
process.env.HEAVY_DEBUG && console.log(`🔎 customComponentsDir ${customComponentsDir}`);
process.env.HEAVY_DEBUG && console.log(`🔎 destination ${destination}`);
const isFile = fs.lstatSync(fileOrDir).isFile();
if (isFile) {
const destPath = path.join(this.spaTmpPath(), targetRoot, destination, relativeFilename);
process.env.HEAVY_DEBUG && console.log(`🔎 Copying file ${fileOrDir} to ${destPath}`);
await fsExtra.copy(fileOrDir, destPath);
return;
} else {
// for now do nothing
}
}
);
watcher.on('fallback', notifyWatcherIssue);
this.allWatchers.push(watcher);
}
async tryReadFile(filePath: string) {
try {
const content = await fs.promises.readFile(filePath, 'utf-8');
return content;
} catch (e) {
// file does not exist
process.env.HEAVY_DEBUG && console.log(`🪲File ${filePath} does not exist, returning null`);
return null;
}
}
async computeSourcesHash(folderPath: string = this.spaTmpPath(), allFiles: string[] = []) {
const files = await fs.promises.readdir(folderPath, { withFileTypes: true });
const hashes = await Promise.all(
files.map(async (file) => {
const filePath = path.join(folderPath, file.name);
// 🚫 Skip big files or files which might be dynamic
if (file.name === 'node_modules' || file.name === 'dist' ||
file.name === 'i18n-messages.json' || file.name === 'i18n-empty.json' ||
file.name === 'hashes.json' || file.name === 'package.json' ||
file.name === 'pnpm-lock.yaml' || file.name === 'package-lock.json') {