-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
211 lines (202 loc) · 7.26 KB
/
index.js
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
/**
* @fileoverview It is a gulp task's obligation to provide a list of resources
* to insert as a value of `global.options['RESOURCES']`.
*/
const fs = require('fs');
const esprima = require('nightly-esprima');
const estraverse = require('estraverse');
const minifyHtml = require('html-minifier').minify;
const CleanCSS = require('clean-css');
const DEFAULT_PREFIX = "RESOURCE_";
const esprimaParseOption = { range: true };
class InlineResource {
constructor(options) {
// Options can be provided as a global property `global.options.RESOURCES`.
if (isUndef(options) && !isUndef(global.options)) {
options = global.options['RESOURCES'];
}
if (isUndef(options)) {
throw new Error("InlineResource: an options object hasn't been provided")
}
this.prefix = options.__prefix || DEFAULT_PREFIX;
this.reResourceVar = new RegExp('^' + this.prefix + '(.*)$');
this.rescCache = new ResourceCache(options, this.prefix);
this.inline = this.inline.bind(this);
}
inline(code) {
if (code.indexOf(this.prefix) === -1) { return code; } // Quick path
const ast = esprima.parseModule(code, esprimaParseOption);
let taskBuffer = [];
const option = new ESTraverseOption(taskBuffer, code, this.rescCache, this.reResourceVar);
estraverse.traverse(ast, option);
let l = taskBuffer.length;
while (l--) {
let task = taskBuffer[l];
code = code.slice(0, task.start) + task.resc + code.slice(task.end);
}
return code;
}
}
const htmlMinifyOption = {
collapseWhitespace: true,
minifyCSS: true,
removeAttributeQuotes: false,
removeComments: false,
removeOptionalTags: true
};
// https://github.com/joliss/js-string-escape/blob/master/index.js
// https://github.com/joliss/js-string-escape/blob/master/LICENSE
const reNeedsEscape = /["\\\n\r\u2028\u2029]/g
class ResourceCache {
constructor(rescMap, prefix) {
this.rescMap = rescMap;
this.prefix = prefix;
this.cache = new Map();
}
getResource(name, options) {
let resourcePath = this.rescMap[name];
let raw;
if (isUndef(resourcePath)) { return null; }
if (typeof resourcePath === 'object') { // typeof resourcePath == { buffer:Buffer, path:string }
let { path, data } = resourcePath;
resourcePath = path;
raw = data.toString();
}
let processed = this.cache.get(resourcePath);
const ext = ResourceCache.getFileExtension(resourcePath);
if (isUndef(processed)) {
if (isUndef(raw)) {
try {
raw = fs.readFileSync(resourcePath).toString();
} catch(e) { return null; } // The prescribed resource does not exist.
}
processed = this.preprocess(raw, ext);
this.cache.set(resourcePath, processed);
}
let intermediate = this.applyOption(processed, ext, options);
let final = this.ensureQuotes(intermediate, ext, options);
return final;
}
static getFileExtension(name) {
let i = name.lastIndexOf('.');
return name.slice(i + 1);
}
preprocess(raw, type) {
switch (type) {
case 'html':
return minifyHtml(raw, htmlMinifyOption);
case 'css':
return (new CleanCSS()).minify(raw).styles;
case 'json':
return JSON.stringify(JSON.parse(raw));
default:
return raw;
}
}
applyOption(resc, type, options) {
if (type === 'json' || isUndef(options)) { return [resc]; }
let keys = Object.getOwnPropertyNames(options);
const regexSrc = `${this.prefix}(${keys.join('|')})`;
const regex = new RegExp(regexSrc);
return resc.split(regex);
}
ensureQuotes(intermediate, type, options) {
const quoteIsNotNeeded = type === 'json' || (type === 'js' && isUndef(options));
if (quoteIsNotNeeded) { return intermediate[0]; }
return intermediate.map((str, index) => {
if ((index & 1) === 0) {
return ResourceCache.quotize(str, type);
} else {
return options[str];
}
}).join("+");
}
static escape(match) {
switch (match) {
case '"':
case "'":
case '\\':
return '\\' + match
case '\n':
return '\\n'
case '\r':
return '\\r'
case '\u2028':
return '\\u2028'
case '\u2029':
return '\\u2029'
}
}
static escapeJs(match) {
switch (match) {
case '"':
case "'":
case '\\':
return '\\' + match
case '\n':
return '\\n\\\n' // Line continuation character for ease
// of reading inlined resource.
case '\r':
return '' // Carriage returns won't have
// any semantic meaning in JS
case '\u2028':
return '\\u2028'
case '\u2029':
return '\\u2029'
}
}
static quotize(resc, type) {
if (type === 'js') {
return `"${resc.replace(reNeedsEscape, ResourceCache.escapeJs)}"`
}
return `"${resc.replace(reNeedsEscape, ResourceCache.escape)}"`
}
}
class ESTraverseOption {
constructor(buffer, code, rescCache, reResourceVar) {
this.buffer = buffer;
this.code = code;
this.rescCache = rescCache;
this.reResourceVar = reResourceVar;
this.enter = this.enter.bind(this);
}
enter(node, parentNode) {
const type = node.type;
if (type === 'Identifier') {
const name = node.name;
const match = this.reResourceVar.exec(name);
if (match === null) { return; }
let rescName = match[1], options, range;
// Matches `RESOURCE_ARGS(RESOURCE_SCRIPT, "SOME_CONSTANT", const_value)`.
if (rescName === "ARGS" && parentNode.type === "CallExpression") {
({ rescName, options } = this.processArgs(parentNode));
range = parentNode.range;
} else {
range = node.range;
}
let resc = this.rescCache.getResource(rescName, options);
if (!resc) { return; } // skip if no resource is provided.
this.buffer.push({
start: range[0],
end: range[1],
resc
});
}
}
processArgs(rescArgNode) {
const args = rescArgNode.arguments;
const rescName = args[0].value;
const options = Object.create(null);
for (let i = 1, l = args.length; i < l; i++) {
let marker = args[i].value;
let cptdNode = args[++i];
let range = cptdNode.range;
options[marker] = this.code.slice(range[0], range[1]);
}
return { rescName, options };
}
}
function isUndef(x) {
return typeof x === 'undefined';
}
module.exports = InlineResource;