-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractParser.ts
198 lines (170 loc) · 4.93 KB
/
AbstractParser.ts
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
import { IFile } from '../IConfig';
import * as babel from 'babel-core';
const template = require('../template');
const { NodeVM, VMScript } = require('vm2');
const mustache = require('mustache');
const pify = require('pify');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
abstract class AbstractParser {
// Reference to file object
protected file:IFile = null;
// Default template for mustache
private static DEFAULT_TEMPLATE:string = template.SCSS_MAP_UNQUOTED;
/**
* @param file
*/
constructor(file:IFile) {
this.file = file;
}
/**
* Flattens compiled object and prepares the object for the mustache template engine
* @param obj
* @returns {IVarMap}
*/
protected mapObject(obj:{[index:string]:any}):IVarMap {
if(!obj) {
return;
}
const varMap:IVarMap = {};
const recurse = (currentObject:any, rootKey?:string) => {
Object.keys(currentObject).forEach((key:string) => {
if (typeof currentObject[key] === 'string' || typeof currentObject[key] === 'number') {
if(rootKey) {
if (!varMap[`${rootKey}`]) {
varMap[`${rootKey}`] = [];
}
varMap[rootKey].push({ keyName: key, keyValue: currentObject[key] })
}
} else if(typeof currentObject[key] === 'object' && currentObject[key] !== null) {
recurse(currentObject[key], key);
}
});
};
recurse(obj);
return varMap;
}
/**
* Transforms the source and then runs it
* @param source
* @returns {Object}
*/
protected evaluateSource(source:string):{[x:string]:string} {
source = this.stripExports(source);
source = this.transformSource(source);
return this.runSource(source);
}
/**
* stripExports omitted which is surrounded by a sassify-disable/enable string
* @param source
* @returns {string}
*/
private stripExports(source:string) : string {
return source.
replace(/^\/\/[\s\S]sassify-disable[\s\S]*sassify-enable\s*$/gm, '').
replace(/\/\*[\s\S]+sassify-disable[\s\S]*sassify-enable[\s\S]*\*\//gm, '');
}
/**
* Transforms the source to ES2015
* @param source
* @returns {string}
*/
private transformSource(source:string):string {
// Transform source to es5
return babel.transform(source, {
ast: false,
presets: [ 'es2015' ],
}).code;
}
/**
* The source code is evaluated through the VM2 (sandbox) module
* @param source
* @returns {Object}
*/
private runSource(source:string):{[x:string]:string} {
// Spawn a new vm
const vm = new NodeVM();
let vmScript = source;
let compiledSource = null;
try {
vmScript = new VMScript(source);
} catch (error) {
console.error('Failed to compile script.');
throw error;
}
try {
compiledSource = vm.run(vmScript);
} catch (error) {
console.error('Failed to execute script.');
throw error;
}
return compiledSource;
}
/**
* Returns the fileName
* @param filePath
* @returns {undefined|string}
*/
private getFileName(filePath:string):string {
return filePath.split(/\//).pop();
}
/**
* Read mustache template file
* @returns {Promise<any>}
*/
private async readTemplate():Promise<any> {
const template = !this.file.template ? AbstractParser.DEFAULT_TEMPLATE : this.file.template;
return pify(fs.readFile)(template, 'utf-8');
}
/**
* Write mustache template file
* @param templateData
* @returns {Promise<any>}
*/
private async writeTemplate(templateData:string):Promise<any> {
const fileToWrite:()=>Promise<any> = () => pify(fs.writeFile)(this.file.dest, templateData, 'utf8');
if (!this.file.disableDirectoryCreation) {
await pify(mkdirp)(path.dirname(this.file.dest));
}
return fileToWrite();
}
/**
* Creation of mustache template
* @param jsObject
* @returns {Promise<void>}
*/
protected async createTemplate(jsObject:{[x:string]:string}):Promise<any> {
const data = this.mapObject(jsObject);
if (data) {
const template = await this.readTemplate();
const dataKeys = Object.keys(data);
let processedTemplate:string = '';
dataKeys.forEach((key, index) => {
// Replace key with map-name/filename if exists (when doing a export default { ... })
if (dataKeys.length === 1) {
const keyCopy = key;
key = this.file.mapName ? this.file.mapName : this.getFileName(this.file.dest)
.split('.')[0].replace(/^_/, '');
// Create a new key and content with the new key name, remove the old key from object
if (key !== keyCopy && data.hasOwnProperty(keyCopy)) {
data[key] = data[keyCopy];
delete data[keyCopy];
}
}
processedTemplate += template.replace(/__rootKey__/g, key);
// Only add two newlines when we are not at EOF
processedTemplate += (index + 1) === dataKeys.length ? "\n" : "\n\n";
});
await this.writeTemplate(mustache.render(processedTemplate, data));
}
}
/**
* Abstract implementation of run
*/
abstract async run():Promise<any>;
}
interface IVarMap {
[index:string]:Array<{keyName:string;keyValue:string}>;
}
export default AbstractParser;