]> git.immae.eu Git - github/fretlink/purs-loader.git/blob - src/index.js
Extract err locations from the format introduced in `purescript@0.12.2`
[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 utils = require('./utils');
30
31 const spawn = require('cross-spawn').sync
32
33 const eol = require('os').EOL
34
35 var CACHE_VAR = {
36 rebuild: false,
37 deferred: [],
38 bundleModules: [],
39 ideServer: null,
40 psModuleMap: null,
41 warnings: [],
42 errors: [],
43 compilationStarted: false,
44 compilationFinished: false,
45 compilationFailed: false,
46 installed: false,
47 srcOption: []
48 };
49
50 module.exports = function purescriptLoader(source, map) {
51 this.cacheable && this.cacheable();
52
53 const webpackContext = (this.options && this.options.context) || this.rootContext;
54
55 const callback = this.async();
56
57 const loaderOptions = loaderUtils.getOptions(this) || {};
58
59 const srcOption = (pscPackage => {
60 const srcPath = path.join('src', '**', '*.purs');
61
62 const bowerPath = path.join('bower_components', 'purescript-*', 'src', '**', '*.purs');
63
64 if (CACHE_VAR.srcOption.length > 0) {
65 return CACHE_VAR.srcOption;
66 }
67 else if (pscPackage) {
68 const pscPackageCommand = 'psc-package';
69
70 const pscPackageArgs = ['sources'];
71
72 const loaderSrc = loaderOptions.src || [
73 srcPath
74 ];
75
76 debug('psc-package %s %o', pscPackageCommand, pscPackageArgs);
77
78 const cmd = spawn(pscPackageCommand, pscPackageArgs);
79
80 if (cmd.error) {
81 throw new Error(cmd.error);
82 }
83 else if (cmd.status !== 0) {
84 const error = cmd.stdout.toString();
85
86 throw new Error(error);
87 }
88 else {
89 const result = cmd.stdout.toString().split(eol).filter(v => v != '').concat(loaderSrc);
90
91 debug('psc-package result: %o', result);
92
93 CACHE_VAR.srcOption = result;
94
95 return result;
96 }
97 }
98 else {
99 const result = loaderOptions.src || [
100 bowerPath,
101 srcPath
102 ];
103
104 CACHE_VAR.srcOption = result;
105
106 return result;
107 }
108 })(loaderOptions.pscPackage);
109
110 const options = Object.assign({
111 context: webpackContext,
112 psc: null,
113 pscArgs: {},
114 pscBundle: null,
115 pscBundleArgs: {},
116 pscIdeClient: null,
117 pscIdeClientArgs: {},
118 pscIdeServer: null,
119 pscIdeServerArgs: {},
120 pscIde: false,
121 pscIdeColors: loaderOptions.psc === 'psa',
122 pscPackage: false,
123 bundleOutput: 'output/bundle.js',
124 bundleNamespace: 'PS',
125 bundle: false,
126 warnings: true,
127 watch: false,
128 output: 'output',
129 src: []
130 }, loaderOptions, {
131 src: srcOption
132 });
133
134 if (!CACHE_VAR.installed) {
135 debugVerbose('installing purs-loader with options: %O', options);
136
137 CACHE_VAR.installed = true;
138
139 // invalidate loader CACHE_VAR when bundle is marked as invalid (in watch mode)
140 this._compiler.plugin('invalid', () => {
141 debugVerbose('invalidating loader CACHE_VAR');
142
143 CACHE_VAR = {
144 rebuild: options.pscIde,
145 deferred: [],
146 bundleModules: [],
147 ideServer: CACHE_VAR.ideServer,
148 psModuleMap: CACHE_VAR.psModuleMap,
149 warnings: [],
150 errors: [],
151 compilationStarted: false,
152 compilationFinished: false,
153 compilationFailed: false,
154 installed: CACHE_VAR.installed,
155 srcOption: []
156 };
157 });
158
159 // add psc warnings to webpack compilation warnings
160 this._compiler.plugin('after-compile', (compilation, callback) => {
161 CACHE_VAR.warnings.forEach(warning => {
162 compilation.warnings.push(warning);
163 });
164
165 CACHE_VAR.errors.forEach(error => {
166 compilation.errors.push(error);
167 });
168
169 callback()
170 });
171 }
172
173 const psModuleName = PsModuleMap.matchModule(source);
174
175 const psModule = {
176 name: psModuleName,
177 source: source,
178 load: ({js, map}) => callback(null, js, map),
179 reject: error => callback(error),
180 srcPath: this.resourcePath,
181 remainingRequest: loaderUtils.getRemainingRequest(this),
182 srcDir: path.dirname(this.resourcePath),
183 jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
184 options: options,
185 cache: CACHE_VAR,
186 emitWarning: warning => {
187 if (options.warnings && warning.length) {
188 CACHE_VAR.warnings.push(warning);
189 }
190 },
191 emitError: pscMessage => {
192 if (pscMessage.length) {
193 const modules = [];
194
195 const matchErrorsSeparator = /\n(?=Error)/;
196 const errors = pscMessage.split(matchErrorsSeparator);
197 for (const error of errors) {
198 const matchErrLocation = /at (.+\.purs):(\d+):(\d+) - (\d+):(\d+) \(line \2, column \3 - line \4, column \5\)/;
199 const [, filename] = matchErrLocation.exec(error) || [];
200 if (!filename) continue;
201
202 const baseModulePath = path.join(this.rootContext, filename);
203 this.addDependency(baseModulePath);
204
205 const matchErrModuleName = /in module ((?:\w+\.)*\w+)/;
206 const [, baseModuleName] = matchErrModuleName.exec(error) || [];
207 if (!baseModuleName) continue;
208
209 const matchMissingModuleName = /Module ((?:\w+\.)*\w+) was not found/;
210 const matchMissingImportFromModuleName = /Cannot import value \w+ from module ((?:\w+\.)*\w+)/;
211 for (const re of [matchMissingModuleName, matchMissingImportFromModuleName]) {
212 const [, targetModuleName] = re.exec(error) || [];
213 if (targetModuleName) {
214 const resolved = utils.resolvePursModule({
215 baseModulePath,
216 baseModuleName,
217 targetModuleName
218 });
219 this.addDependency(resolved);
220 }
221 }
222
223 const desc = {
224 name: baseModuleName,
225 filename: baseModulePath
226 };
227
228 if (typeof this.describePscError === 'function') {
229 const { dependencies = [], details } = this.describePscError(error, desc);
230
231 for (const dep of dependencies) {
232 this.addDependency(dep);
233 }
234
235 Object.assign(desc, details);
236 }
237
238 modules.push(desc);
239 }
240
241 CACHE_VAR.errors.push(new utils.PscError(pscMessage, modules));
242 }
243 }
244 }
245
246 debug('loading %s', psModule.name);
247
248 if (options.bundle) {
249 CACHE_VAR.bundleModules.push(psModule.name);
250 }
251
252 if (CACHE_VAR.rebuild) {
253 const connect = () => {
254 if (!CACHE_VAR.ideServer) {
255 CACHE_VAR.ideServer = true;
256
257 return ide.connect(psModule)
258 .then(ideServer => {
259 CACHE_VAR.ideServer = ideServer;
260 return psModule;
261 })
262 .then(ide.loadWithRetry)
263 .catch(error => {
264 if (CACHE_VAR.ideServer.kill) {
265 debug('ide failed to initially load modules, stopping the ide server process');
266
267 CACHE_VAR.ideServer.kill();
268 }
269
270 CACHE_VAR.ideServer = null;
271
272 return Promise.reject(error);
273 })
274 ;
275 }
276 else {
277 return Promise.resolve(psModule);
278 }
279 };
280
281 const rebuild = () =>
282 ide.rebuild(psModule)
283 .then(() =>
284 toJavaScript(psModule)
285 .then(js => sourceMaps(psModule, js))
286 .then(psModule.load)
287 .catch(psModule.reject)
288 )
289 .catch(error => {
290 if (error instanceof ide.UnknownModuleError) {
291 // Store the modules that trigger a recompile due to an
292 // unknown module error. We need to wait until compilation is
293 // done before loading these files.
294
295 CACHE_VAR.deferred.push(psModule);
296
297 if (!CACHE_VAR.compilationStarted) {
298 CACHE_VAR.compilationStarted = true;
299
300 return compile(psModule)
301 .then(() => {
302 CACHE_VAR.compilationFinished = true;
303 })
304 .then(() =>
305 Promise.map(CACHE_VAR.deferred, psModule =>
306 ide.load(psModule)
307 .then(() => toJavaScript(psModule))
308 .then(js => sourceMaps(psModule, js))
309 .then(psModule.load)
310 )
311 )
312 .catch(error => {
313 CACHE_VAR.compilationFailed = true;
314
315 CACHE_VAR.deferred[0].reject(error);
316
317 CACHE_VAR.deferred.slice(1).forEach(psModule => {
318 psModule.reject(new Error('purs-loader failed'));
319 })
320 })
321 ;
322 } else if (CACHE_VAR.compilationFailed) {
323 CACHE_VAR.deferred.pop().reject(new Error('purs-loader failed'));
324 } else {
325 // The compilation has started. We must wait until it is
326 // done in order to ensure the module map contains all of
327 // the unknown modules.
328 }
329 }
330 else {
331 debug('ide rebuild failed due to an unhandled error: %o', error);
332
333 psModule.reject(error);
334 }
335 })
336 ;
337
338 connect().then(rebuild);
339 }
340 else if (CACHE_VAR.compilationFinished) {
341 debugVerbose('compilation is already finished, loading module %s', psModule.name);
342
343 toJavaScript(psModule)
344 .then(js => sourceMaps(psModule, js))
345 .then(psModule.load)
346 .catch(psModule.reject);
347 }
348 else {
349 // The compilation has not finished yet. We need to wait for
350 // compilation to finish before the loaders run so that references
351 // to compiled output are valid. Push the modules into the CACHE_VAR to
352 // be loaded once the complation is complete.
353
354 CACHE_VAR.deferred.push(psModule);
355
356 if (!CACHE_VAR.compilationStarted) {
357 CACHE_VAR.compilationStarted = true;
358
359 compile(psModule)
360 .then(() => {
361 CACHE_VAR.compilationFinished = true;
362 })
363 .then(() => {
364 if (options.bundle) {
365 return bundle(options, CACHE_VAR.bundleModules);
366 }
367 })
368 .then(() =>
369 Promise.map(CACHE_VAR.deferred, psModule =>
370 toJavaScript(psModule)
371 .then(js => sourceMaps(psModule, js))
372 .then(psModule.load)
373 )
374 )
375 .catch(error => {
376 CACHE_VAR.compilationFailed = true;
377
378 CACHE_VAR.deferred[0].reject(error);
379
380 CACHE_VAR.deferred.slice(1).forEach(psModule => {
381 psModule.reject(new Error('purs-loader failed'));
382 })
383 })
384 ;
385 } else if (CACHE_VAR.compilationFailed) {
386 CACHE_VAR.deferred.pop().reject(new Error('purs-loader failed'));
387 } else {
388 // The complation has started. Nothing to do but wait until it is
389 // done before loading all of the modules.
390 }
391 }
392 }