aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/purs-module-map.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/purs-module-map.js')
-rw-r--r--src/purs-module-map.js74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/purs-module-map.js b/src/purs-module-map.js
new file mode 100644
index 0000000..b906d08
--- /dev/null
+++ b/src/purs-module-map.js
@@ -0,0 +1,74 @@
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
11const debug = require('debug')('purs-loader');
12
13const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i;
14
15const importModuleRegex = /(?:^|\n)\s*import\s+([\w\.]+)/ig;
16
17module.exports.matchModule = function matchModule(str) {
18 const matches = str.match(srcModuleRegex);
19 return matches && matches[1];
20};
21
22module.exports.matchImports = function matchImports(str) {
23 const matches = str.match(importModuleRegex);
24 return (matches || []).map(a => a.replace(/\n?\s*import\s+/i, ''));
25};
26
27module.exports.makeMapEntry = function makeMapEntry(filePurs) {
28 const dirname = path.dirname(filePurs);
29
30 const basename = path.basename(filePurs, '.purs');
31
32 const fileJs = path.join(dirname, `${basename}.js`);
33
34 const result = Promise.props({
35 filePurs: fs.readFileAsync(filePurs, 'utf8'),
36 fileJs: fs.readFileAsync(fileJs, 'utf8').catch(() => undefined)
37 }).then(fileMap => {
38 const sourcePurs = fileMap.filePurs;
39
40 const sourceJs = fileMap.fileJs;
41
42 const moduleName = module.exports.matchModule(sourcePurs);
43
44 const imports = module.exports.matchImports(sourcePurs);
45
46 const map = {};
47
48 map[moduleName] = map[moduleName] || {};
49
50 map[moduleName].src = path.resolve(filePurs);
51
52 map[moduleName].imports = imports;
53
54 if (sourceJs) {
55 map[moduleName].ffi = path.resolve(fileJs);
56 }
57
58 return map;
59 });
60
61 return result;
62};
63
64module.exports.makeMap = function makeMap(src) {
65 debug('loading PureScript source and FFI files from %o', src);
66
67 const globs = [].concat(src);
68
69 return globby(globs).then(paths =>
70 Promise.all(paths.map(module.exports.makeMapEntry)).then(result =>
71 result.reduce(Object.assign, {})
72 )
73 );
74};