diff options
Diffstat (limited to 'src/purs-module-map.js')
-rw-r--r-- | src/purs-module-map.js | 74 |
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 | |||
3 | const path = require('path'); | ||
4 | |||
5 | const Promise = require('bluebird'); | ||
6 | |||
7 | const fs = Promise.promisifyAll(require('fs')); | ||
8 | |||
9 | const globby = require('globby'); | ||
10 | |||
11 | const debug = require('debug')('purs-loader'); | ||
12 | |||
13 | const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i; | ||
14 | |||
15 | const importModuleRegex = /(?:^|\n)\s*import\s+([\w\.]+)/ig; | ||
16 | |||
17 | module.exports.matchModule = function matchModule(str) { | ||
18 | const matches = str.match(srcModuleRegex); | ||
19 | return matches && matches[1]; | ||
20 | }; | ||
21 | |||
22 | module.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 | |||
27 | module.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 | |||
64 | module.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 | }; | ||