Merge pull request #5230 from solgenomics/topic/open_pollinated
[sgn.git] / js / webpack_util / webpack-filemap-plugin.js
blob8f05b2ea03ec8025c0d9902ec33460031fd77fb9
1 // Creates JSON dependency mapping from webpack compilation.
3 const path = require('path');
4 const fs = require('fs');
6 function path_inside(parent, dir) {
7     var relative_path = path.relative(parent, dir);
8     return !!relative_path && !relative_path.startsWith('..') && !path.isAbsolute(relative_path);
11 function FileMapPlugin(options) {
12   this.jsan_re = RegExp(
13     fs.readFileSync(
14       options.legacy_regex, 
15       "utf8"
16     ).replace(/^[\s\n]+|[\s\n]+$/,""),
17     'g'
18   );
21 FileMapPlugin.prototype.apply = function(compiler) {
22   var self = this;
23   compiler.hooks.emit.tapAsync('SGNFileMapPlugin', function(compilation,callback) {
24     var entrypoints = {};
25     var legacy_lists = {};
26     [...compilation.entrypoints].forEach((kvpair)=>{
27       entrypoints[kvpair[0]] = {
28         'files': kvpair[1].chunks.reduce((a,chunk)=>a.concat(chunk.files),[]).filter(f=>f.endsWith(".js")),
29         'legacy': []
30       };
31       entrypoints[kvpair[0]].files.forEach(f=>{
32         legacy_lists[f] = legacy_lists[f] || [];
33         legacy_lists[f].push(entrypoints[kvpair[0]].legacy);
34       })
35     });
36     compilation.chunks.forEach(chunk=>{
37       chunk.files.forEach(f=>{
38         compilation.assets[f].source().replace(self.jsan_re,function(m,g1,g2){
39           legacy_lists[f].forEach(leg_list=>leg_list.push(g1||g2));
40         })
41       });
42     });
43     var entrypoints_string = JSON.stringify(entrypoints,null,2);
44     compilation.assets['mapping.json'] = {
45       source: function() {
46         return entrypoints_string;
47       },
48       size: function() {
49         return entrypoints_string.length;
50       }
51     };
52     callback();
53   });
56 module.exports = FileMapPlugin;