]> git.immae.eu Git - github/fretlink/purs-loader.git/blob - src/Psc.js
Emit warnings/errors to the compilation instance
[github/fretlink/purs-loader.git] / src / Psc.js
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 spawn = require('cross-spawn')
10
11 const debug = require('debug')('purs-loader');
12
13 const dargs = require('./dargs');
14
15 function compile(psModule) {
16 const options = psModule.options
17 const cache = psModule.cache
18 const stderr = []
19
20 if (cache.compilationStarted) return Promise.resolve(psModule)
21
22 cache.compilationStarted = true
23
24 const args = dargs(Object.assign({
25 _: options.src,
26 output: options.output,
27 }, options.pscArgs))
28
29 debug('spawning compiler %s %o', options.psc, args)
30
31 return (new Promise((resolve, reject) => {
32 debug('compiling PureScript...')
33
34 const compilation = spawn(options.psc, args)
35
36 compilation.stderr.on('data', data => {
37 stderr.push(data.toString());
38 });
39
40 compilation.on('close', code => {
41 debug('finished compiling PureScript.')
42 cache.compilationFinished = true
43 if (code !== 0) {
44 const errorMessage = stderr.join('');
45 if (errorMessage.length) {
46 psModule.emitError(errorMessage);
47 }
48 reject(new Error('compilation failed'))
49 } else {
50 const warningMessage = stderr.join('');
51 if (options.warnings && warningMessage.length) {
52 psModule.emitWarning(warningMessage);
53 }
54 resolve(psModule)
55 }
56 })
57 }))
58 .then(compilerOutput => {
59 if (options.bundle) {
60 return bundle(options, cache).then(() => psModule)
61 }
62 return psModule
63 })
64 }
65 module.exports.compile = compile;
66
67 function bundle(options, cache) {
68 if (cache.bundle) return Promise.resolve(cache.bundle)
69
70 const stdout = []
71 const stderr = cache.bundle = []
72
73 const args = dargs(Object.assign({
74 _: [path.join(options.output, '*', '*.js')],
75 output: options.bundleOutput,
76 namespace: options.bundleNamespace,
77 }, options.pscBundleArgs))
78
79 cache.bundleModules.forEach(name => args.push('--module', name))
80
81 debug('spawning bundler %s %o', options.pscBundle, args.join(' '))
82
83 return (new Promise((resolve, reject) => {
84 debug('bundling PureScript...')
85
86 const compilation = spawn(options.pscBundle, args)
87
88 compilation.stdout.on('data', data => stdout.push(data.toString()))
89 compilation.stderr.on('data', data => stderr.push(data.toString()))
90 compilation.on('close', code => {
91 debug('finished bundling PureScript.')
92 if (code !== 0) {
93 const errorMessage = stderr.join('');
94 if (errorMessage.length) {
95 psModule.emitError(errorMessage);
96 }
97 return reject(new Error('bundling failed'))
98 }
99 cache.bundle = stderr
100 resolve(fs.appendFileAsync(options.bundleOutput, `module.exports = ${options.bundleNamespace}`))
101 })
102 }))
103 }