-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
249 lines (197 loc) · 7.49 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
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
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var cloneRegexp = require('clone-regexp');
var shellwords = require('shellwords');
var pascalCase = require('pascal-case');
var loaderUtils = require('loader-utils');
var escapeRegexp = require('escape-string-regexp');
var utils = require('./utils');
var extractHeader = utils.extractHeader;
var DIRECTIVE_PATTERN = utils.DIRECTIVE_PATTERN;
// Gross that it is hardcoded, but webpack doesn't really have the notion
// of mimetypes or all the extensions that _can_ compile down to JS/CSS.
// Likely should make this configurable?
var JS_EXTENSIONS = [
'js',
'coffee',
'jade'
];
var CSS_EXTENSIONS = [
'css',
'scss',
'sass'
];
var IS_CSS_REGEX = new RegExp('\.(' + CSS_EXTENSIONS.map(escapeRegexp).join('|') + ')$', 'i');
var CSS_GLOB = "*.{" + CSS_EXTENSIONS.map(escapeRegexp).join(',') + "}"
var CSS_RECURSIVE_GLOB = "**/" + CSS_GLOB;
function isFromCSSFile(webpackLoader) {
return IS_CSS_REGEX.test(webpackLoader.resourcePath);
}
function isFromCoffeeFile(webpackLoader) {
return path.extname(webpackLoader.resourcePath) == '.coffee';
}
function blockCommentFor(message, webpackLoader) {
if (isFromCoffeeFile(webpackLoader)) {
return '### ' + message + ' ###';
} else {
return '/* ' + message + ' */';
}
}
function ensureDirDoesntStartWithASlash(dir) {
// Remove front slash
if (dir[0] === '/') {
dir = dir.slice(1);
}
return dir;
}
function lookUpDirectoryIn(dirToLookup, rootPathsToCheck, absoluteSourcePath) {
dirToLookup = ensureDirDoesntStartWithASlash(dirToLookup);
// Convert relative path to root-based relative path
if (/^\.\.?\//.test(dirToLookup)) {
for (var i = 0; i < rootPathsToCheck.length; i++) {
if (absoluteSourcePath.startsWith(rootPathsToCheck[i])) {
var relativeSourcePath = absoluteSourcePath.replace(rootPathsToCheck[i], '');
dirToLookup = path.join(path.dirname(relativeSourcePath), dirToLookup)
if (dirToLookup.startsWith('..')) {
throw new Error('Relative path ' + dirToLookup + ' is not allowed to access relative paths outside the original project');
}
break;
}
}
}
dirToLookup = ensureDirDoesntStartWithASlash(dirToLookup);
for (var i = 0; i < rootPathsToCheck.length; i++) {
var fullPathToCheck = path.join(rootPathsToCheck[i], dirToLookup);
try {
// TODO, make async
var stats = fs.statSync(fullPathToCheck);
if (stats.isDirectory()) {
return fullPathToCheck;
}
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
}
return;
}
function buildJSContextRequireString(resolvedDir, dirToRequire, extensions, options) {
options = options || {};
var isRecursive = options.recursive === true;
return [
'// All ' + (isRecursive ? 'recursive ' : '') + extensions.join(', ') + ' files in ' + dirToRequire,
'var req = require.context(',
JSON.stringify(resolvedDir) + ',',
isRecursive + ',', // include subdirectories
'/.*\.(' + extensions.join('|') + ')$/',
');\n' +
'req.keys().forEach(function(key){',
'req(key);',
'});'
].join('\n');
}
function cssRequireString(pathToRequire) {
var importStr;
// Don't mess with relative or absolute paths. Otherwise prefix `~` to
// tell webpack to look up the paths as modules
if (/^(\.|\/)/.test(pathToRequire)) {
importStr = "@import url(" + pathToRequire + ");"
} else {
importStr = "@import url(~" + pathToRequire + ");"
}
return importStr;
}
var DirectiveMethods = {
processRequireDirective: function(webpackLoader, pathToRequire) {
if (isFromCSSFile(webpackLoader)) {
return cssRequireString(pathToRequire);
} else {
return "require(" + loaderUtils.stringifyRequest(webpackLoader, pathToRequire) + ");"
}
},
_processDirectoryHelper: function(directiveName, isRecursive, webpackLoader, dirToRequire) {
var resolvedDir,
locationsToLookIn = [ webpackLoader.options.context];
if (webpackLoader.options.resolve && webpackLoader.options.resolve.root) {
Array.prototype.push.apply(locationsToLookIn, webpackLoader.options.resolve.root);
}
// If the dirToRequire is a relative path
if (/^\.\.?\//.test(dirToRequire)) {
dirToRequire
// CONSIDER, allow??? And ensure that the final resolved path is inside
// locationsToLookIn ?
}
resolvedDir = lookUpDirectoryIn(dirToRequire, locationsToLookIn, webpackLoader.resourcePath);
if (!resolvedDir) {
throw new Error("Couldn't find " + dirToRequire + " in any of " + locationsToLookIn.join(', '))
}
if (isFromCSSFile(webpackLoader)) {
var allCSSFiles = glob.sync(isRecursive ? CSS_RECURSIVE_GLOB : CSS_GLOB, {
cwd: resolvedDir
}).sort();
// Get rid of "partials" (files that start with `_`)
allCSSFiles = allCSSFiles.filter(function(filepath) {
return path.basename(filepath)[0] != '_';
});
// Prefix each file with the original directory path
allCSSFiles = allCSSFiles.map(function(filepath) {
return path.join(dirToRequire, filepath);
})
return allCSSFiles.map(cssRequireString).join('\n');
} else if (isFromCoffeeFile(webpackLoader)) {
return '`' + buildJSContextRequireString(resolvedDir, dirToRequire, JS_EXTENSIONS, {
recursive: isRecursive
}) + '`';
} else {
// TODO, since we need to glob for CSS, should we just do that here too?
// (instead of the fancy WebPack require string?)
return buildJSContextRequireString(resolvedDir, dirToRequire, JS_EXTENSIONS, {
recursive: isRecursive
});
}
},
processRequireTreeDirective: function(webpackLoader, dirToRequire) {
return DirectiveMethods._processDirectoryHelper.call(this, 'require_tree', true, webpackLoader, dirToRequire);
},
processRequireDirectoryDirective: function(webpackLoader, dirToRequire) {
return DirectiveMethods._processDirectoryHelper.call(this, 'require_directory', false, webpackLoader, dirToRequire);
}
}
function processDependenciesInContent(webpackLoader, content) {
webpackLoader.cacheable(true);
// Extract out all the directives from the header (directives can only appear
// at the top of the file)
var header = extractHeader(content);
// clone regex for safety
var directivePattern = cloneRegexp(DIRECTIVE_PATTERN);
var modifiedHeaderLines = [];
while (match = directivePattern.exec(header)) {
var preDirective = match[1];
var directive = match[2];
var directiveArgs = shellwords.split(match[3]);
var directiveFunc = "process" + pascalCase(directive) + "Directive";
if (DirectiveMethods[directiveFunc]) {
var newModifiedHeaderLine = DirectiveMethods[directiveFunc].apply(this, [webpackLoader].concat(directiveArgs));
if (newModifiedHeaderLine) {
modifiedHeaderLines.push(newModifiedHeaderLine);
}
} else {
console.warn("Potentially unknown directive `" + preDirective.trim() + " " + directive + "` ? (found in " + webpackLoader.resourcePath + ")");
}
}
if (modifiedHeaderLines.length > 0) {
content = content.replace(
header,
blockCommentFor('Start webpack directive-loader modifications', webpackLoader) + '\n' +
modifiedHeaderLines.join('\n') + '\n' +
blockCommentFor('End webpack directive-loader modifications', webpackLoader) + '\n\n'
);
}
return content;
}
module.exports = function(source) {
var modifiedSource = processDependenciesInContent(this, source)
return modifiedSource;
};