// @flow

const {Resolver} = require('@parcel/plugin');
const path = require('path');
const {default: NodeResolver} = require('@parcel/node-resolver-core');

module.exports = new Resolver({
  async resolve({dependency, options, specifier}) {
    let mainFields = ['source', 'browser', 'module', 'main'];

    const resolver = new NodeResolver({
      fs: options.inputFS,
      projectRoot: options.projectRoot,
      extensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'css', 'styl', 'vue'],
      mainFields,
    });
    let result = await resolver.resolve({
      filename: specifier,
      specifierType: dependency.specifierType,
      parent: dependency.sourcePath,
      env: dependency.env,
    });
    if (result != null) {
      return {
        ...result,
        canDefer:
          result.filePath != null && path.basename(result.filePath) === 'c.js',
      };
    } else {
      return result;
    }
  },
});
