]> git.immae.eu Git - github/fretlink/purs-loader.git/blob - src/index.js
Fix for webpack4
[github/fretlink/purs-loader.git] / src / index.js
1 'use strict'
2
3 const debug_ = require('debug');
4
5 const debug = debug_('purs-loader');
6
7 const debugVerbose = debug_('purs-loader:verbose');
8
9 const loaderUtils = require('loader-utils')
10
11 const Promise = require('bluebird')
12
13 const path = require('path')
14
15 const PsModuleMap = require('./purs-module-map');
16
17 const compile = require('./compile');
18
19 const bundle = require('./bundle');
20
21 const ide = require('./ide');
22
23 const toJavaScript = require('./to-javascript');
24
25 const sourceMaps = require('./source-maps');
26
27 const dargs = require('./dargs');
28
29 const spawn = require('cross-spawn').sync
30
31 const eol = require('os').EOL
32
33 var CACHE_VAR = {
34 rebuild: false,
35 deferred: [],
36 bundleModules: [],
37 ideServer: null,
38 psModuleMap: null,
39 warnings: [],
40 errors: [],
41 compilationStarted: false,
42 compilationFinished: false,
43 installed: false,
44 srcOption: []
45 };
46
47 module.exports = function purescriptLoader(source, map) {
48 this.cacheable && this.cacheable();
49
50 const webpackContext = (this.options && this.options.context) || this.rootContext;
51
52 const callback = this.async();
53
54 const loaderOptions = loaderUtils.getOptions(this) || {};
55
56 const srcOption = (pscPackage => {
57 const srcPath = path.join('src', '**', '*.purs');
58
59 const bowerPath = path.join('bower_components', 'purescript-*', 'src', '**', '*.purs');
60
61 if (CACHE_VAR.srcOption.length > 0) {
62 return CACHE_VAR.srcOption;
63 }
64 else if (pscPackage) {
65 const pscPackageCommand = 'psc-package';
66
67 const pscPackageArgs = ['sources'];
68
69 const loaderSrc = loaderOptions.src || [
70 srcPath
71 ];
72
73 debug('psc-package %s %o', pscPackageCommand, pscPackageArgs);
74
75 const cmd = spawn(pscPackageCommand, pscPackageArgs);
76
77 if (cmd.error) {
78 throw new Error(cmd.error);
79 }
80 else if (cmd.status !== 0) {
81 const error = cmd.stdout.toString();
82
83 throw new Error(error);
84 }
85 else {
86 const result = cmd.stdout.toString().split(eol).filter(v => v != '').concat(loaderSrc);
87
88 debug('psc-package result: %o', result);
89
90 CACHE_VAR.srcOption = result;
91
92 return result;
93 }
94 }
95 else {
96 const result = loaderOptions.src || [
97 bowerPath,
98 srcPath
99 ];
100
101 CACHE_VAR.srcOption = result;
102
103 return result;
104 }
105 })(loaderOptions.pscPackage);
106
107 const options = Object.assign({
108 context: webpackContext,
109 psc: null,
110 pscArgs: {},
111 pscBundle: null,
112 pscBundleArgs: {},
113 pscIdeClient: null,
114 pscIdeClientArgs: {},
115 pscIdeServer: null,
116 pscIdeServerArgs: {},
117 pscIde: false,
118 pscIdeColors: loaderOptions.psc === 'psa',
119 pscPackage: false,
120 bundleOutput: 'output/bundle.js',
121 bundleNamespace: 'PS',
122 bundle: false,
123 warnings: true,
124 watch: false,
125 output: 'output',
126 src: []
127 }, loaderOptions, {
128 src: srcOption
129 });
130
131 if (!CACHE_VAR.installed) {
132 debugVerbose('installing purs-loader with options: %O', options);
133
134 CACHE_VAR.installed = true;
135
136 // invalidate loader CACHE_VAR when bundle is marked as invalid (in watch mode)
137 this._compiler.plugin('invalid', () => {
138 debugVerbose('invalidating loader CACHE_VAR');
139
140 CACHE_VAR = {
141 rebuild: options.pscIde,
142 deferred: [],
143 bundleModules: [],
144 ideServer: CACHE_VAR.ideServer,
145 psModuleMap: CACHE_VAR.psModuleMap,
146 warnings: [],
147 errors: [],
148 compilationStarted: false,
149 compilationFinished: false,
150 installed: CACHE_VAR.installed,
151 srcOption: []
152 };
153 });
154
155 // add psc warnings to webpack compilation warnings
156 this._compiler.plugin('after-compile', (compilation, callback) => {
157 CACHE_VAR.warnings.forEach(warning => {
158 compilation.warnings.push(warning);
159 });
160
161 CACHE_VAR.errors.forEach(error => {
162 compilation.errors.push(error);
163 });
164
165 callback()
166 });
167 }
168
169 const psModuleName = PsModuleMap.matchModule(source);
170
171 const psModule = {
172 name: psModuleName,
173 source: source,
174 load: ({js, map}) => callback(null, js, map),
175 reject: error => callback(error),
176 srcPath: this.resourcePath,
177 remainingRequest: loaderUtils.getRemainingRequest(this),
178 srcDir: path.dirname(this.resourcePath),
179 jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
180 options: options,
181 cache: CACHE_VAR,
182 emitWarning: warning => {
183 if (options.warnings && warning.length) {
184 CACHE_VAR.warnings.push(warning);
185 }
186 },
187 emitError: error => {
188 if (error.length) {
189 CACHE_VAR.errors.push(error);
190 }
191 }
192 }
193
194 debug('loading %s', psModule.name);
195
196 if (options.bundle) {
197 CACHE_VAR.bundleModules.push(psModule.name);
198 }
199
200 if (CACHE_VAR.rebuild) {
201 const connect = () => {
202 if (!CACHE_VAR.ideServer) {
203 CACHE_VAR.ideServer = true;
204
205 return ide.connect(psModule)
206 .then(ideServer => {
207 CACHE_VAR.ideServer = ideServer;
208 return psModule;
209 })
210 .then(ide.loadWithRetry)
211 .catch(error => {
212 if (CACHE_VAR.ideServer.kill) {
213 debug('ide failed to initially load modules, stopping the ide server process');
214
215 CACHE_VAR.ideServer.kill();
216 }
217
218 CACHE_VAR.ideServer = null;
219
220 return Promise.reject(error);
221 })
222 ;
223 }
224 else {
225 return Promise.resolve(psModule);
226 }
227 };
228
229 const rebuild = () =>
230 ide.rebuild(psModule)
231 .then(() =>
232 toJavaScript(psModule)
233 .then(js => sourceMaps(psModule, js))
234 .then(psModule.load)
235 .catch(psModule.reject)
236 )
237 .catch(error => {
238 if (error instanceof ide.UnknownModuleError) {
239 // Store the modules that trigger a recompile due to an
240 // unknown module error. We need to wait until compilation is
241 // done before loading these files.
242
243 CACHE_VAR.deferred.push(psModule);
244
245 if (!CACHE_VAR.compilationStarted) {
246 CACHE_VAR.compilationStarted = true;
247
248 return compile(psModule)
249 .then(() => {
250 CACHE_VAR.compilationFinished = true;
251 })
252 .then(() =>
253 Promise.map(CACHE_VAR.deferred, psModule =>
254 ide.load(psModule)
255 .then(() => toJavaScript(psModule))
256 .then(js => sourceMaps(psModule, js))
257 .then(psModule.load)
258 )
259 )
260 .catch(error => {
261 CACHE_VAR.deferred[0].reject(error);
262
263 CACHE_VAR.deferred.slice(1).forEach(psModule => {
264 psModule.reject(new Error('purs-loader failed'));
265 })
266 })
267 ;
268 }
269 else {
270 // The compilation has started. We must wait until it is
271 // done in order to ensure the module map contains all of
272 // the unknown modules.
273 }
274 }
275 else {
276 debug('ide rebuild failed due to an unhandled error: %o', error);
277
278 psModule.reject(error);
279 }
280 })
281 ;
282
283 connect().then(rebuild);
284 }
285 else if (CACHE_VAR.compilationFinished) {
286 debugVerbose('compilation is already finished, loading module %s', psModule.name);
287
288 toJavaScript(psModule)
289 .then(js => sourceMaps(psModule, js))
290 .then(psModule.load)
291 .catch(psModule.reject);
292 }
293 else {
294 // The compilation has not finished yet. We need to wait for
295 // compilation to finish before the loaders run so that references
296 // to compiled output are valid. Push the modules into the CACHE_VAR to
297 // be loaded once the complation is complete.
298
299 CACHE_VAR.deferred.push(psModule);
300
301 if (!CACHE_VAR.compilationStarted) {
302 CACHE_VAR.compilationStarted = true;
303
304 compile(psModule)
305 .then(() => {
306 CACHE_VAR.compilationFinished = true;
307 })
308 .then(() => {
309 if (options.bundle) {
310 return bundle(options, CACHE_VAR.bundleModules);
311 }
312 })
313 .then(() =>
314 Promise.map(CACHE_VAR.deferred, psModule =>
315 toJavaScript(psModule)
316 .then(js => sourceMaps(psModule, js))
317 .then(psModule.load)
318 )
319 )
320 .catch(error => {
321 CACHE_VAR.deferred[0].reject(error);
322
323 CACHE_VAR.deferred.slice(1).forEach(psModule => {
324 psModule.reject(new Error('purs-loader failed'));
325 })
326 })
327 ;
328 }
329 else {
330 // The complation has started. Nothing to do but wait until it is
331 // done before loading all of the modules.
332 }
333 }
334 }