UNPKG

2.08 kBPlain TextView Raw
1import * as vm from 'vm';
2import * as fs from 'fs';
3import * as _ from 'lodash';
4import {SystemConfig} from './models';
5
6export function readConfig(cfgCode: string[]) {
7 let cfg: any = {};
8 let configFunc = (systemCfg: any) => {
9 _.merge(cfg, systemCfg);
10 };
11
12 let sandbox = {
13 System: {
14 config: configFunc
15 },
16 SystemJS: {
17 config: configFunc
18 }
19 };
20 vm.createContext(sandbox);
21 cfgCode.forEach(c => {
22 vm.runInContext(c, sandbox);
23 });
24
25 return cfg as SystemConfig;
26}
27
28export function isSystemJS(cfgCode: string) {
29 let res = false;
30 let sandbox = {
31 SystemJS: {
32 config: () => {
33 res = true;
34 }
35 },
36 System: {
37 config: () => {
38 res = false;
39 }
40 }
41 };
42 vm.createContext(sandbox);
43 vm.runInContext(cfgCode, sandbox);
44 return res;
45}
46
47export function isSystem(cfgCode: string) {
48 let res = false;
49 let sandbox = {
50 System: {
51 config: () => {
52 res = true;
53 }
54 },
55 SystemJS: {
56 config: () => {
57 res = false;
58 }
59 }
60 };
61 vm.createContext(sandbox);
62 vm.runInContext(cfgCode, sandbox);
63
64 return res;
65}
66
67export function serializeConfig(config: SystemConfig, isSystemJS: boolean = false) {
68 let tab = ' ';
69 let json = JSON.stringify(config, null, 2)
70 .replace(new RegExp('^' + tab + '"(\\w+)"', 'mg'), tab + '$1');
71
72 if (isSystemJS) {
73 return `SystemJS.config(${json});`;
74 }
75 return `System.config(${json});`;
76}
77
78export function getAppConfig(configPath: string | string[]) {
79 let configCode: string[] = [];
80
81 if (typeof configPath === 'string') {
82 configCode.push(fs.readFileSync(configPath, 'utf8'));
83 }
84
85 if (Array.isArray(configPath)) {
86 configPath.forEach(cp => {
87 configCode.push(fs.readFileSync(cp, 'utf8'));
88 });
89 }
90
91 let appCfg = readConfig(configCode);
92
93 if (!appCfg.map) {
94 appCfg.map = {};
95 }
96 return appCfg;
97}
98
99export function saveAppConfig(configPath: string, config: SystemConfig) {
100 fs.writeFileSync(configPath, serializeConfig(config, isSystemJS(fs.readFileSync(configPath, 'utf8'))));
101}