]> git.immae.eu Git - github/fretlink/purs-loader.git/blame - src/index.js
Add info about possibility to connect to existing `psc-ide-server`
[github/fretlink/purs-loader.git] / src / index.js
CommitLineData
7de41f10
AM
1'use strict'
2
7de41f10
AM
3const debug = require('debug')('purs-loader')
4const loaderUtils = require('loader-utils')
7de41f10
AM
5const Promise = require('bluebird')
6const fs = Promise.promisifyAll(require('fs'))
7de41f10 7const path = require('path')
f8d292fb 8const jsStringEscape = require('js-string-escape')
531c751f 9const PsModuleMap = require('./PsModuleMap');
10const Psc = require('./Psc');
11const PscIde = require('./PscIde');
12const dargs = require('./dargs');
7de41f10 13
7de41f10
AM
14const requireRegex = /require\(['"]\.\.\/([\w\.]+)['"]\)/g
15
16module.exports = function purescriptLoader(source, map) {
17 const callback = this.async()
18 const config = this.options
19 const query = loaderUtils.parseQuery(this.query)
20 const webpackOptions = this.options.purescriptLoader || {}
21
22 const options = Object.assign({
23 context: config.context,
24 psc: 'psc',
25 pscArgs: {},
26 pscBundle: 'psc-bundle',
27 pscBundleArgs: {},
5163b5a2 28 pscIde: false,
7de41f10
AM
29 pscIdeColors: webpackOptions.psc === 'psa' || query.psc === 'psa',
30 pscIdeArgs: {},
31 bundleOutput: 'output/bundle.js',
32 bundleNamespace: 'PS',
33 bundle: false,
34 warnings: true,
35 output: 'output',
36 src: [
37 path.join('src', '**', '*.purs'),
38 path.join('bower_components', 'purescript-*', 'src', '**', '*.purs')
2b2207bd 39 ]
7de41f10
AM
40 }, webpackOptions, query)
41
42 this.cacheable && this.cacheable()
43
44 let cache = config.purescriptLoaderCache = config.purescriptLoaderCache || {
45 rebuild: false,
46 deferred: [],
531c751f 47 bundleModules: []
7de41f10
AM
48 }
49
50 if (!config.purescriptLoaderInstalled) {
51 config.purescriptLoaderInstalled = true
52
53 // invalidate loader cache when bundle is marked as invalid (in watch mode)
54 this._compiler.plugin('invalid', () => {
531c751f 55 debug('invalidating loader cache');
56
7de41f10 57 cache = config.purescriptLoaderCache = {
5163b5a2 58 rebuild: options.pscIde,
7de41f10 59 deferred: [],
531c751f 60 bundleModules: [],
61 ideServer: cache.ideServer,
62 psModuleMap: cache.psModuleMap
7de41f10
AM
63 }
64 })
65
66 // add psc warnings to webpack compilation warnings
67 this._compiler.plugin('after-compile', (compilation, callback) => {
9dc10210
AM
68 if (options.warnings && cache.warnings) {
69 compilation.warnings.unshift(`PureScript compilation:\n${cache.warnings}`)
0b853815 70 cache.warnings = null;
7de41f10
AM
71 }
72
9dc10210
AM
73 if (cache.errors) {
74 compilation.errors.unshift(`PureScript compilation:\n${cache.errors}`)
0b853815 75 cache.errors = null;
7de41f10
AM
76 }
77
78 callback()
79 })
80 }
81
531c751f 82 const psModuleName = PsModuleMap.match(source)
7de41f10
AM
83 const psModule = {
84 name: psModuleName,
85 load: js => callback(null, js),
86 reject: error => callback(error),
87 srcPath: this.resourcePath,
88 srcDir: path.dirname(this.resourcePath),
89 jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
90 options: options,
91 cache: cache,
92 }
93
67888496
AM
94 debug('loader called', psModule.name)
95
7de41f10
AM
96 if (options.bundle) {
97 cache.bundleModules.push(psModule.name)
98 }
99
100 if (cache.rebuild) {
531c751f 101 return PscIde.connect(psModule)
102 .then(PscIde.rebuild)
7de41f10
AM
103 .then(toJavaScript)
104 .then(psModule.load)
105 .catch(psModule.reject)
106 }
107
67888496 108 if (cache.compilationFinished) {
7de41f10
AM
109 return toJavaScript(psModule).then(psModule.load).catch(psModule.reject)
110 }
111
112 // We need to wait for compilation to finish before the loaders run so that
113 // references to compiled output are valid.
114 cache.deferred.push(psModule)
115
67888496 116 if (!cache.compilationStarted) {
531c751f 117 return Psc.compile(psModule)
118 .then(() => PsModuleMap.makeMap(options.src).then(map => {
119 debug('rebuilt module map');
120 cache.psModuleMap = map;
121 }))
7de41f10
AM
122 .then(() => Promise.map(cache.deferred, psModule => {
123 if (typeof cache.ideServer === 'object') cache.ideServer.kill()
124 return toJavaScript(psModule).then(psModule.load)
125 }))
126 .catch(error => {
127 cache.deferred[0].reject(error)
4b99e432 128 cache.deferred.slice(1).forEach(psModule => psModule.reject(new Error('purs-loader failed')))
7de41f10
AM
129 })
130 }
131}
132
531c751f 133function updatePsModuleMap(psModule) {
134 const options = psModule.options
135 const cache = psModule.cache
136 const filePurs = psModule.srcPath
137 if (!cache.psModuleMap) {
138 debug('module mapping does not exist');
139 return PsModuleMap.makeMap(options.src).then(map => {
140 cache.psModuleMap = map;
141 return cache.psModuleMap;
142 });
143 }
144 else {
145 return PsModuleMap.makeMapEntry(filePurs).then(result => {
146 const map = Object.assign(cache.psModuleMap, result)
147 cache.psModuleMap = map;
148 return cache.psModuleMap;
149 });
150 }
151}
152
7de41f10
AM
153// The actual loader is executed *after* purescript compilation.
154function toJavaScript(psModule) {
155 const options = psModule.options
156 const cache = psModule.cache
157 const bundlePath = path.resolve(options.bundleOutput)
158 const jsPath = cache.bundle ? bundlePath : psModule.jsPath
159
67888496 160 debug('loading JavaScript for', psModule.name)
7de41f10
AM
161
162 return Promise.props({
163 js: fs.readFileAsync(jsPath, 'utf8'),
531c751f 164 psModuleMap: updatePsModuleMap(psModule)
7de41f10
AM
165 }).then(result => {
166 let js = ''
167
168 if (options.bundle) {
169 // if bundling, return a reference to the bundle
170 js = 'module.exports = require("'
f8d292fb 171 + jsStringEscape(path.relative(psModule.srcDir, options.bundleOutput))
7de41f10
AM
172 + '")["' + psModule.name + '"]'
173 } else {
174 // replace require paths to output files generated by psc with paths
175 // to purescript sources, which are then also run through this loader.
7de41f10
AM
176 js = result.js
177 .replace(requireRegex, (m, p1) => {
f8d292fb 178 return 'require("' + jsStringEscape(result.psModuleMap[p1].src) + '")'
17acb575
AM
179 })
180 .replace(/require\(['"]\.\/foreign['"]\)/g, (m, p1) => {
f8d292fb 181 return 'require("' + jsStringEscape(result.psModuleMap[psModule.name].ffi) + '")'
7de41f10 182 })
7de41f10
AM
183 }
184
185 return js
186 })
187}