]> git.immae.eu Git - github/fretlink/purs-loader.git/blobdiff - src/index.js
Watch foreign modules on compilation error
[github/fretlink/purs-loader.git] / src / index.js
index 6bf1e09e169c4678dae210285c12ed764e5dde7d..be809c685ac5959cc011388259cea1026578102c 100644 (file)
 'use strict'
 
-const colors = require('chalk')
-const debug = require('debug')('purs-loader')
+const debug_ = require('debug');
+
+const debug = debug_('purs-loader');
+
+const debugVerbose = debug_('purs-loader:verbose');
+
 const loaderUtils = require('loader-utils')
-const globby = require('globby')
+
 const Promise = require('bluebird')
-const fs = Promise.promisifyAll(require('fs'))
-const spawn = require('cross-spawn')
+
 const path = require('path')
-const retryPromise = require('promise-retry')
 
-const ffiModuleRegex = /\/\/\s+module\s+([\w\.]+)/i
-const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i
-const requireRegex = /require\(['"]\.\.\/([\w\.]+)['"]\)/g
+const PsModuleMap = require('./purs-module-map');
 
-module.exports = function purescriptLoader(source, map) {
-  const callback = this.async()
-  const config = this.options
-  const query = loaderUtils.parseQuery(this.query)
-  const webpackOptions = this.options.purescriptLoader || {}
+const compile = require('./compile');
 
-  const options = Object.assign({
-    context: config.context,
-    psc: 'psc',
-    pscArgs: {},
-    pscBundle: 'psc-bundle',
-    pscBundleArgs: {},
-    pscIde: false,
-    pscIdeColors: webpackOptions.psc === 'psa' || query.psc === 'psa',
-    pscIdeArgs: {},
-    bundleOutput: 'output/bundle.js',
-    bundleNamespace: 'PS',
-    bundle: false,
-    warnings: true,
-    output: 'output',
-    src: [
-      path.join('src', '**', '*.purs'),
-      path.join('bower_components', 'purescript-*', 'src', '**', '*.purs')
-    ],
-    ffi: [
-      path.join('src', '**', '*.js'),
-      path.join('bower_components', 'purescript-*', 'src', '**', '*.js')
-    ],
-  }, webpackOptions, query)
-
-  this.cacheable && this.cacheable()
-
-  let cache = config.purescriptLoaderCache = config.purescriptLoaderCache || {
-    rebuild: false,
-    deferred: [],
-    bundleModules: [],
-  }
+const bundle = require('./bundle');
 
-  if (!config.purescriptLoaderInstalled) {
-    config.purescriptLoaderInstalled = true
+const ide = require('./ide');
 
-    // invalidate loader cache when bundle is marked as invalid (in watch mode)
-    this._compiler.plugin('invalid', () => {
-      cache = config.purescriptLoaderCache = {
-        rebuild: options.pscIde,
-        deferred: [],
-        ideServer: cache.ideServer
-      }
-    })
+const toJavaScript = require('./to-javascript');
 
-    // add psc warnings to webpack compilation warnings
-    this._compiler.plugin('after-compile', (compilation, callback) => {
-      if (options.warnings && cache.warnings) {
-        compilation.warnings.unshift(`PureScript compilation:\n${cache.warnings}`)
-      }
+const sourceMaps = require('./source-maps');
 
-      if (cache.errors) {
-        compilation.errors.unshift(`PureScript compilation:\n${cache.errors}`)
-      }
+const dargs = require('./dargs');
 
-      callback()
-    })
-  }
+const utils = require('./utils');
 
-  const psModuleName = match(srcModuleRegex, source)
-  const psModule = {
-    name: psModuleName,
-    load: js => callback(null, js),
-    reject: error => callback(error),
-    srcPath: this.resourcePath,
-    srcDir: path.dirname(this.resourcePath),
-    jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
-    options: options,
-    cache: cache,
-  }
+const spawn = require('cross-spawn').sync
 
-  debug('loader called', psModule.name)
+const eol = require('os').EOL
 
-  if (options.bundle) {
-    cache.bundleModules.push(psModule.name)
-  }
+var CACHE_VAR = {
+  rebuild: false,
+  deferred: [],
+  bundleModules: [],
+  ideServer: null,
+  psModuleMap: null,
+  warnings: [],
+  errors: [],
+  compilationStarted: false,
+  compilationFinished: false,
+  compilationFailed: false,
+  installed: false,
+  srcOption: []
+};
 
-  if (cache.rebuild) {
-    return connectIdeServer(psModule)
-      .then(rebuild)
-      .then(toJavaScript)
-      .then(psModule.load)
-      .catch(psModule.reject)
-  }
+module.exports = function purescriptLoader(source, map) {
+  this.cacheable && this.cacheable();
 
-  if (cache.compilationFinished) {
-    return toJavaScript(psModule).then(psModule.load).catch(psModule.reject)
-  }
+  const webpackContext = (this.options && this.options.context) || this.rootContext;
 
-  // We need to wait for compilation to finish before the loaders run so that
-  // references to compiled output are valid.
-  cache.deferred.push(psModule)
+  const callback = this.async();
 
-  if (!cache.compilationStarted) {
-    return compile(psModule)
-      .then(() => Promise.map(cache.deferred, psModule => {
-        if (typeof cache.ideServer === 'object') cache.ideServer.kill()
-        return toJavaScript(psModule).then(psModule.load)
-      }))
-      .catch(error => {
-        cache.deferred[0].reject(error)
-        cache.deferred.slice(1).forEach(psModule => psModule.reject(true))
-      })
-  }
-}
+  const loaderOptions = loaderUtils.getOptions(this) || {};
 
-// The actual loader is executed *after* purescript compilation.
-function toJavaScript(psModule) {
-  const options = psModule.options
-  const cache = psModule.cache
-  const bundlePath = path.resolve(options.bundleOutput)
-  const jsPath = cache.bundle ? bundlePath : psModule.jsPath
-
-  debug('loading JavaScript for', psModule.name)
-
-  return Promise.props({
-    js: fs.readFileAsync(jsPath, 'utf8'),
-    psModuleMap: psModuleMap(options, cache)
-  }).then(result => {
-    let js = ''
-
-    if (options.bundle) {
-      // if bundling, return a reference to the bundle
-      js = 'module.exports = require("'
-             + path.relative(psModule.srcDir, options.bundleOutput)
-             + '")["' + psModule.name + '"]'
-    } else {
-      // replace require paths to output files generated by psc with paths
-      // to purescript sources, which are then also run through this loader.
-      js = result.js
-        .replace(requireRegex, (m, p1) => {
-          return 'require("' + result.psModuleMap[p1].src + '")'
-        })
-        .replace(/require\(['"]\.\/foreign['"]\)/g, (m, p1) => {
-          return 'require("' + result.psModuleMap[psModule.name].ffi + '")'
-        })
-    }
+  const srcOption = (pscPackage => {
+    const srcPath = path.join('src', '**', '*.purs');
 
-    return js
-  })
-}
+    const bowerPath = path.join('bower_components', 'purescript-*', 'src', '**', '*.purs');
+
+    if (CACHE_VAR.srcOption.length > 0) {
+      return CACHE_VAR.srcOption;
+    }
+    else if (pscPackage) {
+      const pscPackageCommand = 'psc-package';
 
-function compile(psModule) {
-  const options = psModule.options
-  const cache = psModule.cache
-  const stderr = []
+      const pscPackageArgs = ['sources'];
 
-  if (cache.compilationStarted) return Promise.resolve(psModule)
+      const loaderSrc = loaderOptions.src || [
+        srcPath
+      ];
 
-  cache.compilationStarted = true
+      debug('psc-package %s %o', pscPackageCommand, pscPackageArgs);
 
-  const args = dargs(Object.assign({
-    _: options.src,
-    ffi: options.ffi,
-    output: options.output,
-  }, options.pscArgs))
+      const cmd = spawn(pscPackageCommand, pscPackageArgs);
 
-  debug('spawning compiler %s %o', options.psc, args)
+      if (cmd.error) {
+        throw new Error(cmd.error);
+      }
+      else if (cmd.status !== 0) {
+        const error = cmd.stdout.toString();
 
-  return (new Promise((resolve, reject) => {
-    console.log('\nCompiling PureScript...')
+        throw new Error(error);
+      }
+      else {
+        const result = cmd.stdout.toString().split(eol).filter(v => v != '').concat(loaderSrc);
 
-    const compilation = spawn(options.psc, args)
+        debug('psc-package result: %o', result);
 
-    compilation.stdout.on('data', data => stderr.push(data.toString()))
-    compilation.stderr.on('data', data => stderr.push(data.toString()))
+        CACHE_VAR.srcOption = result;
 
-    compilation.on('close', code => {
-      console.log('Finished compiling PureScript.')
-      cache.compilationFinished = true
-      if (code !== 0) {
-        cache.errors = stderr.join('')
-        reject(true)
-      } else {
-        cache.warnings = stderr.join('')
-        resolve(psModule)
+        return result;
       }
-    })
-  }))
-  .then(compilerOutput => {
-    if (options.bundle) {
-      return bundle(options, cache).then(() => psModule)
     }
-    return psModule
-  })
-}
+    else {
+      const result = loaderOptions.src || [
+        bowerPath,
+        srcPath
+      ];
 
-function rebuild(psModule) {
-  const options = psModule.options
-  const cache = psModule.cache
+      CACHE_VAR.srcOption = result;
 
-  debug('attempting rebuild with psc-ide-client %s', psModule.srcPath)
+      return result;
+    }
+  })(loaderOptions.pscPackage);
 
-  const request = (body) => new Promise((resolve, reject) => {
-    const args = dargs(options.pscIdeArgs)
-    const ideClient = spawn('psc-ide-client', args)
+  const options = Object.assign({
+    context: webpackContext,
+    psc: null,
+    pscArgs: {},
+    pscBundle: null,
+    pscBundleArgs: {},
+    pscIdeClient: null,
+    pscIdeClientArgs: {},
+    pscIdeServer: null,
+    pscIdeServerArgs: {},
+    pscIde: false,
+    pscIdeColors: loaderOptions.psc === 'psa',
+    pscPackage: false,
+    bundleOutput: 'output/bundle.js',
+    bundleNamespace: 'PS',
+    bundle: false,
+    warnings: true,
+    watch: false,
+    output: 'output',
+    src: []
+  }, loaderOptions, {
+    src: srcOption
+  });
 
-    var stdout = ''
-    var stderr = ''
+  if (!CACHE_VAR.installed) {
+    debugVerbose('installing purs-loader with options: %O', options);
 
-    ideClient.stdout.on('data', data => {
-      stdout = stdout + data.toString()
-    })
+    CACHE_VAR.installed = true;
 
-    ideClient.stderr.on('data', data => {
-      stderr = stderr + data.toString()
-    })
+    // invalidate loader CACHE_VAR when bundle is marked as invalid (in watch mode)
+    this._compiler.plugin('invalid', () => {
+      debugVerbose('invalidating loader CACHE_VAR');
 
-    ideClient.on('close', code => {
-      if (code !== 0) {
-        const error = stderr === '' ? 'Failed to spawn psc-ide-client' : stderr
-        return reject(new Error(error))
-      }
+      CACHE_VAR = {
+        rebuild: options.pscIde,
+        deferred: [],
+        bundleModules: [],
+        ideServer: CACHE_VAR.ideServer,
+        psModuleMap: CACHE_VAR.psModuleMap,
+        warnings: [],
+        errors: [],
+        compilationStarted: false,
+        compilationFinished: false,
+        compilationFailed: false,
+        installed: CACHE_VAR.installed,
+        srcOption: []
+      };
+    });
 
-      let res = null
+    // add psc warnings to webpack compilation warnings
+    this._compiler.plugin('after-compile', (compilation, callback) => {
+      CACHE_VAR.warnings.forEach(warning => {
+        compilation.warnings.push(warning);
+      });
 
-      try {
-        res = JSON.parse(stdout.toString())
-        debug(res)
-      } catch (err) {
-        return reject(err)
-      }
+      CACHE_VAR.errors.forEach(error => {
+        compilation.errors.push(error);
+      });
 
-      if (res && !Array.isArray(res.result)) {
-        return res.resultType === 'success'
-               ? resolve(psModule)
-               : reject('psc-ide rebuild failed')
+      callback()
+    });
+  }
+
+  const psModuleName = PsModuleMap.matchModule(source);
+
+  const psModule = {
+    name: psModuleName,
+    source: source,
+    load: ({js, map}) => callback(null, js, map),
+    reject: error => callback(error),
+    srcPath: this.resourcePath,
+    remainingRequest: loaderUtils.getRemainingRequest(this),
+    srcDir: path.dirname(this.resourcePath),
+    jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
+    options: options,
+    cache: CACHE_VAR,
+    emitWarning: warning => {
+      if (options.warnings && warning.length) {
+        CACHE_VAR.warnings.push(warning);
       }
+    },
+    emitError: pscMessage => {
+      if (pscMessage.length) {
+        const modules = [];
+
+        const matchErrorsSeparator = /\n(?=Error)/;
+        const errors = pscMessage.split(matchErrorsSeparator);
+        for (const error of errors) {
+          const matchErrLocation = /at (.+\.purs):(\d+):(\d+) - (\d+):(\d+) \(line \2, column \3 - line \4, column \5\)/;
+          const [, filename] = matchErrLocation.exec(error) || [];
+          if (!filename) continue;
+
+          const baseModulePath = path.join(this.rootContext, filename);
+          this.addDependency(baseModulePath);
+
+          const foreignModulesErrorCodes = [
+            'ErrorParsingFFIModule',
+            'MissingFFIImplementations',
+            'UnusedFFIImplementations',
+            'MissingFFIModule'
+          ];
+          for (const code of foreignModulesErrorCodes) {
+            if (error.includes(code)) {
+              const resolved = utils.resolveForeignModule(baseModulePath);
+              this.addDependency(resolved);
+            }
+          }
 
-      Promise.map(res.result, (item, i) => {
-        debug(item)
-        return formatIdeResult(item, options, i, res.result.length)
-      })
-      .then(compileMessages => {
-        if (res.resultType === 'error') {
-          if (res.result.some(item => item.errorCode === 'UnknownModule')) {
-            console.log('Unknown module, attempting full recompile')
-            return compile(psModule)
-              .then(() => request({ command: 'load' }))
-              .then(resolve)
-              .catch(() => reject('psc-ide rebuild failed'))
+          const matchErrModuleName = /in module ((?:\w+\.)*\w+)/;
+          const [, baseModuleName] = matchErrModuleName.exec(error) || [];
+          if (!baseModuleName) continue;
+
+          const matchMissingModuleName = /Module ((?:\w+\.)*\w+) was not found/;
+          const matchMissingImportFromModuleName = /Cannot import value \w+ from module ((?:\w+\.)*\w+)/;
+          for (const re of [matchMissingModuleName, matchMissingImportFromModuleName]) {
+            const [, targetModuleName] = re.exec(error) || [];
+            if (targetModuleName) {
+              const resolved = utils.resolvePursModule({
+                baseModulePath,
+                baseModuleName,
+                targetModuleName
+              });
+              this.addDependency(resolved);
+            }
           }
-          cache.errors = compileMessages.join('\n')
-          reject('psc-ide rebuild failed')
-        } else {
-          cache.warnings = compileMessages.join('\n')
-          resolve(psModule)
-        }
-      })
-    })
 
-    ideClient.stdin.write(JSON.stringify(body))
-    ideClient.stdin.write('\n')
-  })
+          const desc = {
+            name: baseModuleName,
+            filename: baseModulePath
+          };
 
-  return request({
-    command: 'rebuild',
-    params: {
-      file: psModule.srcPath,
-    }
-  })
-}
+          if (typeof this.describePscError === 'function') {
+            const { dependencies = [], details } = this.describePscError(error, desc);
 
-function formatIdeResult(result, options, index, length) {
-  const srcPath = path.relative(options.context, result.filename)
-  const pos = result.position
-  const fileAndPos = `${srcPath}:${pos.startLine}:${pos.startColumn}`
-  let numAndErr = `[${index+1}/${length} ${result.errorCode}]`
-  numAndErr = options.pscIdeColors ? colors.yellow(numAndErr) : numAndErr
-
-  return fs.readFileAsync(result.filename, 'utf8').then(source => {
-    const lines = source.split('\n').slice(pos.startLine - 1, pos.endLine)
-    const endsOnNewline = pos.endColumn === 1 && pos.startLine !== pos.endLine
-    const up = options.pscIdeColors ? colors.red('^') : '^'
-    const down = options.pscIdeColors ? colors.red('v') : 'v'
-    let trimmed = lines.slice(0)
-
-    if (endsOnNewline) {
-      lines.splice(lines.length - 1, 1)
-      pos.endLine = pos.endLine - 1
-      pos.endColumn = lines[lines.length - 1].length || 1
-    }
+            for (const dep of dependencies) {
+              this.addDependency(dep);
+            }
 
-    // strip newlines at the end
-    if (endsOnNewline) {
-      trimmed = lines.reverse().reduce((trimmed, line, i) => {
-        if (i === 0 && line === '') trimmed.trimming = true
-        if (!trimmed.trimming) trimmed.push(line)
-        if (trimmed.trimming && line !== '') {
-          trimmed.trimming = false
-          trimmed.push(line)
-        }
-        return trimmed
-      }, []).reverse()
-      pos.endLine = pos.endLine - (lines.length - trimmed.length)
-      pos.endColumn = trimmed[trimmed.length - 1].length || 1
-    }
+            Object.assign(desc, details);
+          }
 
-    const spaces = ' '.repeat(String(pos.endLine).length)
-    let snippet = trimmed.map((line, i) => {
-      return `  ${pos.startLine + i}  ${line}`
-    }).join('\n')
+          modules.push(desc);
+        }
 
-    if (trimmed.length === 1) {
-      snippet += `\n  ${spaces}  ${' '.repeat(pos.startColumn - 1)}${up.repeat(pos.endColumn - pos.startColumn + 1)}`
-    } else {
-      snippet = `  ${spaces}  ${' '.repeat(pos.startColumn - 1)}${down}\n${snippet}`
-      snippet += `\n  ${spaces}  ${' '.repeat(pos.endColumn - 1)}${up}`
+        CACHE_VAR.errors.push(new utils.PscError(pscMessage, modules));
+      }
     }
+  }
 
-    return Promise.resolve(
-      `\n${numAndErr} ${fileAndPos}\n\n${snippet}\n\n${result.message}`
-    )
-  })
-}
-
-function bundle(options, cache) {
-  if (cache.bundle) return Promise.resolve(cache.bundle)
-
-  const stdout = []
-  const stderr = cache.bundle = []
-
-  const args = dargs(Object.assign({
-    _: [path.join(options.output, '*', '*.js')],
-    output: options.bundleOutput,
-    namespace: options.bundleNamespace,
-  }, options.pscBundleArgs))
-
-  cache.bundleModules.forEach(name => args.push('--module', name))
+  debug('loading %s', psModule.name);
 
-  debug('spawning bundler %s %o', options.pscBundle, args.join(' '))
+  if (options.bundle) {
+    CACHE_VAR.bundleModules.push(psModule.name);
+  }
 
-  return (new Promise((resolve, reject) => {
-    console.log('Bundling PureScript...')
+  if (CACHE_VAR.rebuild) {
+    const connect = () => {
+      if (!CACHE_VAR.ideServer) {
+        CACHE_VAR.ideServer = true;
+
+        return ide.connect(psModule)
+          .then(ideServer => {
+            CACHE_VAR.ideServer = ideServer;
+            return psModule;
+          })
+          .then(ide.loadWithRetry)
+          .catch(error => {
+            if (CACHE_VAR.ideServer.kill) {
+              debug('ide failed to initially load modules, stopping the ide server process');
+
+              CACHE_VAR.ideServer.kill();
+            }
+
+            CACHE_VAR.ideServer = null;
+
+            return Promise.reject(error);
+          })
+        ;
+      }
+      else {
+        return Promise.resolve(psModule);
+      }
+    };
+
+    const rebuild = () =>
+      ide.rebuild(psModule)
+      .then(() =>
+        toJavaScript(psModule)
+          .then(js => sourceMaps(psModule, js))
+          .then(psModule.load)
+          .catch(psModule.reject)
+      )
+      .catch(error => {
+        if (error instanceof ide.UnknownModuleError) {
+          // Store the modules that trigger a recompile due to an
+          // unknown module error. We need to wait until compilation is
+          // done before loading these files.
 
-    const compilation = spawn(options.pscBundle, args)
+          CACHE_VAR.deferred.push(psModule);
 
-    compilation.stdout.on('data', data => stdout.push(data.toString()))
-    compilation.stderr.on('data', data => stderr.push(data.toString()))
-    compilation.on('close', code => {
-      if (code !== 0) {
-        cache.errors = (cache.errors || '') + stderr.join('')
-        return reject(true)
-      }
-      cache.bundle = stderr
-      resolve(fs.appendFileAsync('output/bundle.js', `module.exports = ${options.bundleNamespace}`))
-    })
-  }))
-}
+          if (!CACHE_VAR.compilationStarted) {
+            CACHE_VAR.compilationStarted = true;
 
-// map of PS module names to their source path
-function psModuleMap(options, cache) {
-  if (cache.psModuleMap) return Promise.resolve(cache.psModuleMap)
-
-  const globs = [].concat(options.src).concat(options.ffi)
-
-  return globby(globs).then(paths => {
-    return Promise
-      .props(paths.reduce((map, file) => {
-        map[file] = fs.readFileAsync(file, 'utf8')
-        return map
-      }, {}))
-      .then(fileMap => {
-        cache.psModuleMap = Object.keys(fileMap).reduce((map, file) => {
-          const source = fileMap[file]
-          const ext = path.extname(file)
-          const isPurs = ext.match(/purs$/i)
-          const moduleRegex = isPurs ? srcModuleRegex : ffiModuleRegex
-          const moduleName = match(moduleRegex, source)
-          map[moduleName] = map[moduleName] || {}
-          if (isPurs) {
-            map[moduleName].src = path.resolve(file)
+            return compile(psModule)
+              .then(() => {
+                CACHE_VAR.compilationFinished = true;
+              })
+              .then(() =>
+                Promise.map(CACHE_VAR.deferred, psModule =>
+                  ide.load(psModule)
+                    .then(() => toJavaScript(psModule))
+                    .then(js => sourceMaps(psModule, js))
+                    .then(psModule.load)
+                )
+              )
+              .catch(error => {
+                CACHE_VAR.compilationFailed = true;
+
+                CACHE_VAR.deferred[0].reject(error);
+
+                CACHE_VAR.deferred.slice(1).forEach(psModule => {
+                  psModule.reject(new Error('purs-loader failed'));
+                })
+              })
+            ;
+          } else if (CACHE_VAR.compilationFailed) {
+            CACHE_VAR.deferred.pop().reject(new Error('purs-loader failed'));
           } else {
-            map[moduleName].ffi = path.resolve(file)
+            // The compilation has started. We must wait until it is
+            // done in order to ensure the module map contains all of
+            // the unknown modules.
           }
-          return map
-        }, {})
-        return cache.psModuleMap
-      })
-  })
-}
-
-function connectIdeServer(psModule) {
-  const options = psModule.options
-  const cache = psModule.cache
+        }
+        else {
+          debug('ide rebuild failed due to an unhandled error: %o', error);
 
-  if (cache.ideServer) return Promise.resolve(psModule)
+          psModule.reject(error);
+        }
+      })
+    ;
 
-  cache.ideServer = true
+    connect().then(rebuild);
+  }
+  else if (CACHE_VAR.compilationFinished) {
+    debugVerbose('compilation is already finished, loading module %s', psModule.name);
 
-  const connect = () => new Promise((resolve, reject) => {
-    const args = dargs(options.pscIdeArgs)
+    toJavaScript(psModule)
+      .then(js => sourceMaps(psModule, js))
+      .then(psModule.load)
+      .catch(psModule.reject);
+  }
+  else {
+    // The compilation has not finished yet. We need to wait for
+    // compilation to finish before the loaders run so that references
+    // to compiled output are valid. Push the modules into the CACHE_VAR to
+    // be loaded once the complation is complete.
 
-    debug('attempting to connect to psc-ide-server', args)
+    CACHE_VAR.deferred.push(psModule);
 
-    const ideClient = spawn('psc-ide-client', args)
+    if (!CACHE_VAR.compilationStarted) {
+      CACHE_VAR.compilationStarted = true;
 
-    ideClient.stderr.on('data', data => {
-      debug(data.toString())
-      cache.ideServer = false
-      reject(true)
-    })
-    ideClient.stdout.once('data', data => {
-      debug(data.toString())
-      if (data.toString()[0] === '{') {
-        const res = JSON.parse(data.toString())
-        if (res.resultType === 'success') {
-          cache.ideServer = ideServer
-          resolve(psModule)
-        } else {
-          cache.ideServer = ideServer
-          reject(true)
-        }
-      } else {
-        cache.ideServer = false
-        reject(true)
-      }
-    })
-    ideClient.stdin.resume()
-    ideClient.stdin.write(JSON.stringify({ command: 'load' }))
-    ideClient.stdin.write('\n')
-  })
-
-  const args = dargs(Object.assign({
-    outputDirectory: options.output,
-  }, options.pscIdeArgs))
-
-  debug('attempting to start psc-ide-server', args)
-
-  const ideServer = cache.ideServer = spawn('psc-ide-server', [])
-  ideServer.stderr.on('data', data => {
-    debug(data.toString())
-  })
-
-  return retryPromise((retry, number) => {
-    return connect().catch(error => {
-      if (!cache.ideServer && number === 9) {
-        debug(error)
-
-        console.log(
-          'failed to connect to or start psc-ide-server, ' +
-          'full compilation will occur on rebuild'
+      compile(psModule)
+        .then(() => {
+          CACHE_VAR.compilationFinished = true;
+        })
+        .then(() => {
+          if (options.bundle) {
+            return bundle(options, CACHE_VAR.bundleModules);
+          }
+        })
+        .then(() =>
+          Promise.map(CACHE_VAR.deferred, psModule =>
+            toJavaScript(psModule)
+              .then(js => sourceMaps(psModule, js))
+              .then(psModule.load)
+          )
         )
+        .catch(error => {
+          CACHE_VAR.compilationFailed = true;
 
-        return Promise.resolve(psModule)
-      }
-
-      return retry(error)
-    })
-  }, {
-    retries: 9,
-    factor: 1,
-    minTimeout: 333,
-    maxTimeout: 333,
-  })
-}
-
-function match(regex, str) {
-  const matches = str.match(regex)
-  return matches && matches[1]
-}
-
-function dargs(obj) {
-  return Object.keys(obj).reduce((args, key) => {
-    const arg = '--' + key.replace(/[A-Z]/g, '-$&').toLowerCase();
-    const val = obj[key]
-
-    if (key === '_') val.forEach(v => args.push(v))
-    else if (Array.isArray(val)) val.forEach(v => args.push(arg, v))
-    else args.push(arg, obj[key])
+          CACHE_VAR.deferred[0].reject(error);
 
-    return args.filter(arg => (typeof arg !== 'boolean'))
-  }, [])
+          CACHE_VAR.deferred.slice(1).forEach(psModule => {
+            psModule.reject(new Error('purs-loader failed'));
+          })
+        })
+      ;
+    } else if (CACHE_VAR.compilationFailed) {
+      CACHE_VAR.deferred.pop().reject(new Error('purs-loader failed'));
+    } else {
+      // The complation has started. Nothing to do but wait until it is
+      // done before loading all of the modules.
+    }
+  }
 }