-
Notifications
You must be signed in to change notification settings - Fork 59
/
VirtualModulePlugin.ts
302 lines (260 loc) · 9.01 KB
/
VirtualModulePlugin.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
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
/* eslint-disable no-underscore-dangle */
// taken from https://github.com/sysgears/webpack-virtual-modules/commit/ace8630bae211e297d1de0408c65c4d54f41b187
import path from 'path';
import util from 'util';
import webpack from 'webpack';
import VirtualStats from 'webpack-virtual-modules/virtual-stats';
const debug = util.debuglog('webpack-virtual-modules');
let inode = 45000000;
function createWebpackData(result: any) {
return (backendOrStorage: any) => {
// In Webpack v5, this variable is a "Backend", and has the data stored in a field
// _data. In V4, the `_` prefix isn't present.
if (backendOrStorage._data) {
return {
result,
level: backendOrStorage._levels[backendOrStorage._currentLevel],
};
}
// Webpack 4
return [null, result];
};
}
function getData(storage, key) {
// Webpack 5
if (storage._data instanceof Map) {
return storage._data.get(key);
}
if (storage._data) {
return storage.data[key];
}
if (storage.data instanceof Map) {
// Webpack v4
return storage.data.get(key);
}
return storage.data[key];
}
function setData(backendOrStorage, key, valueFactory) {
const value = valueFactory(backendOrStorage);
// Webpack v5
if (backendOrStorage._data instanceof Map) {
backendOrStorage._data.set(key, value);
} else if (backendOrStorage._data) {
backendOrStorage.data[key] = value;
} else if (backendOrStorage.data instanceof Map) {
// Webpack 4
backendOrStorage.data.set(key, value);
} else {
backendOrStorage.data[key] = value;
}
}
function getStatStorage(fileSystem) {
if (fileSystem._statStorage) {
// Webpack v4
return fileSystem._statStorage;
}
if (fileSystem._statBackend) {
// webpack v5
return fileSystem._statBackend;
}
// Unknown version?
throw new Error("Couldn't find a stat storage");
}
function getFileStorage(fileSystem) {
if (fileSystem._readFileStorage) {
// Webpack v4
return fileSystem._readFileStorage;
}
if (fileSystem._readFileBackend) {
// Webpack v5
return fileSystem._readFileBackend;
}
throw new Error("Couldn't find a readFileStorage");
}
function getReadDirBackend(fileSystem) {
if (fileSystem._readdirBackend) {
return fileSystem._readdirBackend;
}
if (fileSystem._readdirStorage) {
return fileSystem._readdirStorage;
}
throw new Error("Couldn't find a readDirStorage from Webpack Internals");
}
class VirtualModulesPlugin {
private watcher: any;
private compiler: any;
static bootstrap(compilation) {
const { compiler } = compilation;
const plugin = new VirtualModulesPlugin();
VirtualModulesPlugin.augmentFileSystem(compiler);
plugin.apply(compiler);
return plugin;
}
addFile = (filePath: string, contents: string) => {
return this.writeModule(filePath, contents);
};
writeModule(filePath: string, contents: string) {
if (!this.compiler) {
throw new Error(
'You must use this plugin only after creating webpack instance!',
);
}
const len = contents ? contents.length : 0;
const time = Date.now();
const date = new Date(time);
const stats = new VirtualStats({
dev: 8675309,
nlink: 0,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: inode++,
mode: 33188,
size: len,
blocks: Math.floor(len / 4096),
atime: date,
mtime: date,
ctime: date,
birthtime: date,
});
debug(this.compiler.name, 'Write module:', filePath, contents);
// When using the WatchIgnorePlugin (https://github.com/webpack/webpack/blob/52184b897f40c75560b3630e43ca642fcac7e2cf/lib/WatchIgnorePlugin.js),
// the original watchFileSystem is stored in `wfs`. The following "unwraps" the ignoring
// wrappers, giving us access to the "real" watchFileSystem.
let finalWatchFileSystem = this.watcher && this.watcher.watchFileSystem;
while (finalWatchFileSystem && finalWatchFileSystem.wfs) {
finalWatchFileSystem = finalWatchFileSystem.wfs;
}
let finalInputFileSystem = this.compiler.inputFileSystem;
while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
finalInputFileSystem = finalInputFileSystem._inputFileSystem;
}
finalInputFileSystem._writeVirtualFile(filePath, stats, contents);
if (
finalWatchFileSystem &&
(finalWatchFileSystem.watcher.fileWatchers.size ||
finalWatchFileSystem.watcher.fileWatchers.length)
) {
const fileWatchers =
'size' in finalWatchFileSystem.watcher.fileWatchers
? Array.from(finalWatchFileSystem.watcher.fileWatchers.values())
: finalWatchFileSystem.watcher.fileWatchers;
fileWatchers.forEach((fileWatcher) => {
const fileWatcherPath = fileWatcher.path || fileWatcher.watcher.path;
if (fileWatcherPath === filePath) {
const fileWatcherDirectoryWatcher = fileWatcher.directoryWatcher || fileWatcher.watcher.directoryWatcher;
debug(this.compiler.name, 'Emit file change:', filePath, time);
// delete fileWatcherDirectoryWatcher._cachedTimeInfoEntries;
fileWatcherDirectoryWatcher.setFileTime(
filePath,
time,
false,
false,
null,
);
// fileWatcher.emit('change', time, null);
}
});
}
}
static augmentFileSystem(compiler: webpack.Compiler) {
let finalInputFileSystem = compiler.inputFileSystem as any;
while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
finalInputFileSystem = finalInputFileSystem._inputFileSystem;
}
if (!finalInputFileSystem._writeVirtualFile) {
const originalPurge = finalInputFileSystem.purge;
finalInputFileSystem.purge = function purge(...args) {
originalPurge.apply(this, args);
if (this._virtualFiles) {
Object.keys(this._virtualFiles).forEach((file) => {
const data = this._virtualFiles[file];
this._writeVirtualFile(file, data.stats, data.contents);
});
}
};
finalInputFileSystem._writeVirtualFile = function writeVirtualFile(
file: string,
stats: any,
contents: string,
) {
const statStorage = getStatStorage(this);
const fileStorage = getFileStorage(this);
const readDirStorage = getReadDirBackend(this);
this._virtualFiles = this._virtualFiles || {};
this._virtualFiles[file] = { stats, contents };
setData(statStorage, file, createWebpackData(stats));
setData(fileStorage, file, createWebpackData(contents));
if (compiler.fileTimestamps instanceof Map) {
// FIXME
compiler.fileTimestamps.set(file, +stats.mtime as any);
}
const segments = file.split(/[\\/]/);
let count = segments.length - 1;
const minCount = segments[0] ? 1 : 0;
while (count > minCount) {
const dir = segments.slice(0, count).join(path.sep) || path.sep;
try {
finalInputFileSystem.readdirSync(dir);
} catch (e) {
const time = Date.now();
const dirStats = new VirtualStats({
dev: 8675309,
nlink: 0,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: inode++,
mode: 16877,
size: stats.size,
blocks: Math.floor(stats.size / 4096),
atime: time,
mtime: time,
ctime: time,
birthtime: time,
});
setData(readDirStorage, dir, createWebpackData([]));
setData(statStorage, dir, createWebpackData(dirStats));
}
let dirData = getData(readDirStorage, dir);
// Webpack v4 returns an array, webpack v5 returns an object
dirData = dirData[1] || dirData.result;
const filename = segments[count];
if (dirData.indexOf(filename) < 0) {
const files = dirData.concat([filename]).sort();
setData(getReadDirBackend(this), dir, createWebpackData(files));
} else {
break;
}
count--;
}
};
}
}
apply(compiler: webpack.Compiler) {
this.compiler = compiler;
const watchRunHook = (watcher, callback) => {
this.watcher = watcher.compiler || watcher;
if (webpack.version.startsWith('4')) {
const virtualFiles = (compiler.inputFileSystem as any)._virtualFiles;
if (virtualFiles) {
Object.keys(virtualFiles).forEach((file) => {
if (compiler.fileTimestamps instanceof Map)
compiler.fileTimestamps.set(
file,
+virtualFiles[file].stats.mtime as any,
);
});
}
}
callback();
};
// compiler.hooks.afterEnvironment.tap('VirtualModulesPlugin', () => {
// VirtualModulesPlugin.afterEnvironmentHook(compiler);
// });
compiler.hooks.watchRun.tapAsync('VirtualModulesPlugin', watchRunHook);
}
}
export default VirtualModulesPlugin;