]> git.immae.eu Git - github/fretlink/purs-loader.git/blame - src/PsModuleMap.js
Fix rebuild for ModuleNotFound
[github/fretlink/purs-loader.git] / src / PsModuleMap.js
CommitLineData
531c751f 1'use strict';
2
3const path = require('path');
4
5const Promise = require('bluebird');
6
7const fs = Promise.promisifyAll(require('fs'));
8
9const globby = require('globby');
10
8e21ab0a 11const debug = require('debug')('purs-loader');
531c751f 12
8e21ab0a 13const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i;
531c751f 14
8e21ab0a 15const importModuleRegex = /(?:^|\n)\s*import\s+([\w\.]+)/ig;
16
17function matchModule(str) {
531c751f 18 const matches = str.match(srcModuleRegex);
19 return matches && matches[1];
20}
8e21ab0a 21module.exports.match = matchModule;
22
23function matchImports(str) {
24 const matches = str.match(importModuleRegex);
25 return (matches || []).map(a => a.replace(/\n?\s*import\s+/i, ''));
26}
27module.exports.matchImports = matchImports;
531c751f 28
29function makeMapEntry(filePurs) {
30 const dirname = path.dirname(filePurs);
31
32 const basename = path.basename(filePurs, '.purs');
33
34 const fileJs = path.join(dirname, `${basename}.js`);
35
36 const result = Promise.props({
37 filePurs: fs.readFileAsync(filePurs, 'utf8'),
38 fileJs: fs.readFileAsync(fileJs, 'utf8').catch(() => undefined)
39 }).then(fileMap => {
40 const sourcePurs = fileMap.filePurs;
41
42 const sourceJs = fileMap.fileJs;
43
8e21ab0a 44 const moduleName = matchModule(sourcePurs);
45
46 const imports = matchImports(sourcePurs);
531c751f 47
48 const map = {};
49
50 map[moduleName] = map[moduleName] || {};
51
52 map[moduleName].src = path.resolve(filePurs);
53
8e21ab0a 54 map[moduleName].imports = imports;
55
531c751f 56 if (sourceJs) {
57 map[moduleName].ffi = path.resolve(fileJs);
58 }
59
60 return map;
61 });
62
63 return result;
64}
65module.exports.makeMapEntry = makeMapEntry;
66
67function makeMap(src) {
68 debug('loading PureScript source and FFI files from %o', src);
69
70 const globs = [].concat(src);
71
72 return globby(globs).then(paths =>
73 Promise.all(paths.map(makeMapEntry)).then(result =>
74 result.reduce(Object.assign, {})
75 )
76 );
77}
78module.exports.makeMap = makeMap;