code:
let featureQueries = require('caniuse-lite/data/features/css-featurequeries.js')
let feature = require('caniuse-lite/dist/unpacker/feature')
let { parse } = require('postcss')

let Browsers = require('./browsers')
let brackets = require('./brackets')
let Value = require('./value')
let utils = require('./utils')

let data = feature(featureQueries)

let supported = []
for (let browser in data.stats) {
  let versions = data.stats[browser]
  for (let version in versions) {
    let support = versions[version]
    if (/y/.test(support)) {
      supported.push(browser + ' ' + version)
    }
  }
}

class Supports {
  constructor(Prefixes, all) {
    this.Prefixes = Prefixes
    this.all = all
  }

  /**
   * Add prefixes
   */
  add(nodes, all) {
    return nodes.map(i => {
      if (this.isProp(i)) {
        let prefixed = this.prefixed(i[0])
        if (prefixed.length > 1) {
          return this.convert(prefixed)
        }

        return i
      }

      if (typeof i === 'object') {
        return this.add(i, all)
      }

      return i
    })
  }

  /**
   * Clean brackets with one child
   */
  cleanBrackets(nodes) {
    return nodes.map(i => {
      if (typeof i !== 'object') {
        return i
      }

      if (i.length === 1 && typeof i[0] === 'object') {
        return this.cleanBrackets(i[0])
      }

      return this.cleanBrackets(i)
    })
  }

  /**
   * Add " or " between properties and convert it to brackets format
   */
  convert(progress) {
    let result = ['']
    for (let i of progress) {
      result.push([`${i.prop}: ${i.value}`])
      result.push(' or ')
    }
    result[result.length - 1] = ''
    return result
  }

  /**
   * Check global options
   */
  disabled(node) {
    if (!this.all.options.grid) {
      if (node.prop === 'display' && node.value.includes('grid')) {
        return true
      }
      if (node.prop.includes('grid') || node.prop === 'justify-items') {
        return true
      }
    }

    if (this.all.options.flexbox === false) {
      if (node.prop === 'display' && node.value.includes('flex')) {
        return true
      }
      let other = ['order', 'justify-content', 'align-items', 'align-content']
      if (node.prop.includes('flex') || other.includes(node.prop)) {
        return true
      }
    }

    return false
  }

  /**
   * Return true if prefixed property has no unprefixed
   */
  isHack(all, unprefixed) {
    let check = new RegExp(`(\\(|\\s)${utils.escapeRegexp(unprefixed)}:`)
    return !check.test(all)
  }

  /**
   * Return true if brackets node is "not" word
   */
  isNot(node) {
    return typeof node === 'string' && /not\s*/i.test(node)
  }

  /**
   * Return true if brackets node is "or" word
   */
  isOr(node) {
    return typeof node === 'string' && /\s*or\s*/i.test(node)
  }

  /**
   * Return true if brackets node is (prop: value)
   */
  isProp(node) {
    return (
      typeof node === 'object' &&
      node.length === 1 &&
      typeof node[0] === 'string'
    )
  }

  /**
   * Compress value functions into a string nodes
   */
  normalize(nodes) {
    if (typeof nodes !== 'object') {
      return nodes
    }

    nodes = nodes.filter(i => i !== '')

    if (typeof nodes[0] === 'string') {
      let firstNode = nodes[0].trim()

      if (
        firstNode.includes(':') ||
        firstNode === 'selector' ||
        firstNode === 'not selector'
      ) {
        return [brackets.stringify(nodes)]
      }
    }
    return nodes.map(i => this.normalize(i))
  }

  /**
   * Parse string into declaration property and value
   */
  parse(str) {
    let parts = str.split(':')
    let prop = parts[0]
    let value = parts[1]
    if (!value) value = ''
    return [prop.trim(), value.trim()]
  }

  /**
   * Return array of Declaration with all necessary prefixes
   */
  prefixed(str) {
    let rule = this.virtual(str)
    if (this.disabled(rule.first)) {
      return rule.nodes
    }

    let result = { warn: () => null }

    let prefixer = this.prefixer().add[rule.first.prop]
    prefixer && prefixer.process && prefixer.process(rule.first, result)

    for (let decl of rule.nodes) {
      for (let value of this.prefixer().values('add', rule.first.prop)) {
        value.process(decl)
      }
      Value.save(this.all, decl)
    }

    return rule.nodes
  }

  /**
   * Return prefixer only with @supports supported browsers
   */
  prefixer() {
    if (this.prefixerCache) {
      return this.prefixerCache
    }

    let filtered = this.all.browsers.selected.filter(i => {
      return supported.includes(i)
    })

    let browsers = new Browsers(
      this.all.browsers.data,
      filtered,
      this.all.options
    )
    this.prefixerCache = new this.Prefixes(
      this.all.data,
      browsers,
      this.all.options
    )
    return this.prefixerCache
  }

  /**
   * Add prefixed declaration
   */
  process(rule) {
    let ast = brackets.parse(rule.params)
    ast = this.normalize(ast)
    ast = this.remove(ast, rule.params)
    ast = this.add(ast, rule.params)
    ast = this.cleanBrackets(ast)
    rule.params = brackets.stringify(ast)
  }

  /**
   * Remove all unnecessary prefixes
   */
  remove(nodes, all) {
    let i = 0
    while (i < nodes.length) {
      if (
        !this.isNot(nodes[i - 1]) &&
        this.isProp(nodes[i]) &&
        this.isOr(nodes[i + 1])
      ) {
        if (this.toRemove(nodes[i][0], all)) {
          nodes.splice(i, 2)
          continue
        }

        i += 2
        continue
      }

      if (typeof nodes[i] === 'object') {
        nodes[i] = this.remove(nodes[i], all)
      }

      i += 1
    }
    return nodes
  }

  /**
   * Return true if we need to remove node
   */
  toRemove(str, all) {
    let [prop, value] = this.parse(str)
    let unprefixed = this.all.unprefixed(prop)

    let cleaner = this.all.cleaner()

    if (
      cleaner.remove[prop] &&
      cleaner.remove[prop].remove &&
      !this.isHack(all, unprefixed)
    ) {
      return true
    }

    for (let checker of cleaner.values('remove', unprefixed)) {
      if (checker.check(value)) {
        return true
      }
    }

    return false
  }

  /**
   * Create virtual rule to process it by prefixer
   */
  virtual(str) {
    let [prop, value] = this.parse(str)
    let rule = parse('a{}').first
    rule.append({ prop, raws: { before: '' }, value })
    return rule
  }
}

module.exports = Supports


code:
let { list } = require('postcss')
let parser = require('postcss-value-parser')

let Browsers = require('./browsers')
let vendor = require('./vendor')

class Transition {
  constructor(prefixes) {
    this.props = ['transition', 'transition-property']
    this.prefixes = prefixes
  }

  /**
   * Process transition and add prefixes for all necessary properties
   */
  add(decl, result) {
    let prefix, prop
    let add = this.prefixes.add[decl.prop]
    let vendorPrefixes = this.ruleVendorPrefixes(decl)
    let declPrefixes = vendorPrefixes || (add && add.prefixes) || []

    let params = this.parse(decl.value)
    let names = params.map(i => this.findProp(i))
    let added = []

    if (names.some(i => i[0] === '-')) {
      return
    }

    for (let param of params) {
      prop = this.findProp(param)
      if (prop[0] === '-') continue

      let prefixer = this.prefixes.add[prop]
      if (!prefixer || !prefixer.prefixes) continue

      for (prefix of prefixer.prefixes) {
        if (vendorPrefixes && !vendorPrefixes.some(p => prefix.includes(p))) {
          continue
        }

        let prefixed = this.prefixes.prefixed(prop, prefix)
        if (prefixed !== '-ms-transform' && !names.includes(prefixed)) {
          if (!this.disabled(prop, prefix)) {
            added.push(this.clone(prop, prefixed, param))
          }
        }
      }
    }

    params = params.concat(added)
    let value = this.stringify(params)

    let webkitClean = this.stringify(
      this.cleanFromUnprefixed(params, '-webkit-')
    )
    if (declPrefixes.includes('-webkit-')) {
      this.cloneBefore(decl, `-webkit-${decl.prop}`, webkitClean)
    }
    this.cloneBefore(decl, decl.prop, webkitClean)
    if (declPrefixes.includes('-o-')) {
      let operaClean = this.stringify(this.cleanFromUnprefixed(params, '-o-'))
      this.cloneBefore(decl, `-o-${decl.prop}`, operaClean)
    }

    for (prefix of declPrefixes) {
      if (prefix !== '-webkit-' && prefix !== '-o-') {
        let prefixValue = this.stringify(
          this.cleanOtherPrefixes(params, prefix)
        )
        this.cloneBefore(decl, prefix + decl.prop, prefixValue)
      }
    }

    if (value !== decl.value && !this.already(decl, decl.prop, value)) {
      this.checkForWarning(result, decl)
      decl.cloneBefore()
      decl.value = value
    }
  }

  /**
   * Does we already have this declaration
   */
  already(decl, prop, value) {
    return decl.parent.some(i => i.prop === prop && i.value === value)
  }

  /**
   * Show transition-property warning
   */
  checkForWarning(result, decl) {
    if (decl.prop !== 'transition-property') {
      return
    }

    let isPrefixed = false
    let hasAssociatedProp = false

    decl.parent.each(i => {
      if (i.type !== 'decl') {
        return undefined
      }
      if (i.prop.indexOf('transition-') !== 0) {
        return undefined
      }
      let values = list.comma(i.value)
      // check if current Rule's transition-property comma separated value list needs prefixes
      if (i.prop === 'transition-property') {
        values.forEach(value => {
          let lookup = this.prefixes.add[value]
          if (lookup && lookup.prefixes && lookup.prefixes.length > 0) {
            isPrefixed = true
          }
        })
        return undefined
      }
      // check if another transition-* prop in current Rule has comma separated value list
      hasAssociatedProp = hasAssociatedProp || values.length > 1
      return false
    })

    if (isPrefixed && hasAssociatedProp) {
      decl.warn(
        result,
        'Replace transition-property to transition, ' +
          'because Autoprefixer could not support ' +
          'any cases of transition-property ' +
          'and other transition-*'
      )
    }
  }

  /**
   * Remove all non-webkit prefixes and unprefixed params if we have prefixed
   */
  cleanFromUnprefixed(params, prefix) {
    let remove = params
      .map(i => this.findProp(i))
      .filter(i => i.slice(0, prefix.length) === prefix)
      .map(i => this.prefixes.unprefixed(i))

    let result = []
    for (let param of params) {
      let prop = this.findProp(param)
      let p = vendor.prefix(prop)
      if (!remove.includes(prop) && (p === prefix || p === '')) {
        result.push(param)
      }
    }
    return result
  }

  cleanOtherPrefixes(params, prefix) {
    return params.filter(param => {
      let current = vendor.prefix(this.findProp(param))
      return current === '' || current === prefix
    })
  }

  /**
   * Return new param array with different name
   */
  clone(origin, name, param) {
    let result = []
    let changed = false
    for (let i of param) {
      if (!changed && i.type === 'word' && i.value === origin) {
        result.push({ type: 'word', value: name })
        changed = true
      } else {
        result.push(i)
      }
    }
    return result
  }

  /**
   * Add declaration if it is not exist
   */
  cloneBefore(decl, prop, value) {
    if (!this.already(decl, prop, value)) {
      decl.cloneBefore({ prop, value })
    }
  }

  /**
   * Check property for disabled by option
   */
  disabled(prop, prefix) {
    let other = ['order', 'justify-content', 'align-self', 'align-content']
    if (prop.includes('flex') || other.includes(prop)) {
      if (this.prefixes.options.flexbox === false) {
        return true
      }

      if (this.prefixes.options.flexbox === 'no-2009') {
        return prefix.includes('2009')
      }
    }
    return undefined
  }

  /**
   * Find or create separator
   */
  div(params) {
    for (let param of params) {
      for (let node of param) {
        if (node.type === 'div' && node.value === ',') {
          return node
        }
      }
    }
    return { after: ' ', type: 'div', value: ',' }
  }

  /**
   * Find property name
   */
  findProp(param) {
    let prop = param[0].value
    if (/^\d/.test(prop)) {
      for (let [i, token] of param.entries()) {
        if (i !== 0 && token.type === 'word') {
          return token.value
        }
      }
    }
    return prop
  }

  /**
   * Parse properties list to array
   */
  parse(value) {
    let ast = parser(value)
    let result = []
    let param = []
    for (let node of ast.nodes) {
      param.push(node)
      if (node.type === 'div' && node.value === ',') {
        result.push(param)
        param = []
      }
    }
    result.push(param)
    return result.filter(i => i.length > 0)
  }

  /**
   * Process transition and remove all unnecessary properties
   */
  remove(decl) {
    let params = this.parse(decl.value)
    params = params.filter(i => {
      let prop = this.prefixes.remove[this.findProp(i)]
      return !prop || !prop.remove
    })
    let value = this.stringify(params)

    if (decl.value === value) {
      return
    }

    if (params.length === 0) {
      decl.remove()
      return
    }

    let double = decl.parent.some(i => {
      return i.prop === decl.prop && i.value === value
    })
    let smaller = decl.parent.some(i => {
      return i !== decl && i.prop === decl.prop && i.value.length > value.length
    })

    if (double || smaller) {
      decl.remove()
      return
    }

    decl.value = value
  }

  /**
   * Check if transition prop is inside vendor specific rule
   */
  ruleVendorPrefixes(decl) {
    let { parent } = decl

    if (parent.type !== 'rule') {
      return false
    } else if (!parent.selector.includes(':-')) {
      return false
    }

    let selectors = Browsers.prefixes().filter(s =>
      parent.selector.includes(':' + s)
    )

    return selectors.length > 0 ? selectors : false
  }

  /**
   * Return properties string from array
   */
  stringify(params) {
    if (params.length === 0) {
      return ''
    }
    let nodes = []
    for (let param of params) {
      if (param[param.length - 1].type !== 'div') {
        param.push(this.div(params))
      }
      nodes = nodes.concat(param)
    }
    if (nodes[0].type === 'div') {
      nodes = nodes.slice(1)
    }
    if (nodes[nodes.length - 1].type === 'div') {
      nodes = nodes.slice(0, +-2 + 1 || undefined)
    }
    return parser.stringify({ nodes })
  }
}

module.exports = Transition

license: mit


code:
let { list } = require('postcss')

/**
 * Throw special error, to tell beniary,
 * that this error is from Autoprefixer.
 */
module.exports.error = function (text) {
  let err = new Error(text)
  err.autoprefixer = true
  throw err
}

/**
 * Return array, that doesn’t contain duplicates.
 */
module.exports.uniq = function (array) {
  return [...new Set(array)]
}

/**
 * Return "-webkit-" on "-webkit- old"
 */
module.exports.removeNote = function (string) {
  if (!string.includes(' ')) {
    return string
  }

  return string.split(' ')[0]
}

/**
 * Escape RegExp symbols
 */
module.exports.escapeRegexp = function (string) {
  return string.replace(/[$()*+-.?[\\\]^{|}]/g, '\\$&')
}

/**
 * Return regexp to check, that CSS string contain word
 */
module.exports.regexp = function (word, escape = true) {
  if (escape) {
    word = this.escapeRegexp(word)
  }
  return new RegExp(`(^|[\\s,(])(${word}($|[\\s(,]))`, 'gi')
}

/**
 * Change comma list
 */
module.exports.editList = function (value, callback) {
  let origin = list.comma(value)
  let changed = callback(origin, [])

  if (origin === changed) {
    return value
  }

  let join = value.match(/,\s*/)
  join = join ? join[0] : ', '
  return changed.join(join)
}

/**
 * Split the selector into parts.
 * It returns 3 level deep array because selectors can be comma
 * separated (1), space separated (2), and combined (3)
 * @param {String} selector selector string
 * @return {Array<Array<Array>>} 3 level deep array of split selector
 * @see utils.test.js for examples
 */
module.exports.splitSelector = function (selector) {
  return list.comma(selector).map(i => {
    return list.space(i).map(k => {
      return k.split(/(?=\.|#)/g)
    })
  })
}

/**
 * Return true if a given value only contains numbers.
 * @param {*} value
 * @returns {boolean}
 */
module.exports.isPureNumber = function (value) {
  if (typeof value === 'number') {
    return true
  }
  if (typeof value === 'string') {
    return /^[0-9]+$/.test(value)
  }
  return false
}


code:
let Prefixer = require('./prefixer')
let OldValue = require('./old-value')
let vendor = require('./vendor')
let utils = require('./utils')

class Value extends Prefixer {
  /**
   * Clone decl for each prefixed values
   */
  static save(prefixes, decl) {
    let prop = decl.prop
    let result = []

    for (let prefix in decl._autoprefixerValues) {
      let value = decl._autoprefixerValues[prefix]

      if (value === decl.value) {
        continue
      }

      let item
      let propPrefix = vendor.prefix(prop)

      if (propPrefix === '-pie-') {
        continue
      }

      if (propPrefix === prefix) {
        item = decl.value = value
        result.push(item)
        continue
      }

      let prefixed = prefixes.prefixed(prop, prefix)
      let rule = decl.parent

      if (!rule.every(i => i.prop !== prefixed)) {
        result.push(item)
        continue
      }

      let trimmed = value.replace(/\s+/, ' ')
      let already = rule.some(
        i => i.prop === decl.prop && i.value.replace(/\s+/, ' ') === trimmed
      )

      if (already) {
        result.push(item)
        continue
      }

      let cloned = this.clone(decl, { value })
      item = decl.parent.insertBefore(decl, cloned)

      result.push(item)
    }

    return result
  }

  /**
   * Save values with next prefixed token
   */
  add(decl, prefix) {
    if (!decl._autoprefixerValues) {
      decl._autoprefixerValues = {}
    }
    let value = decl._autoprefixerValues[prefix] || this.value(decl)

    let before
    do {
      before = value
      value = this.replace(value, prefix)
      if (value === false) return
    } while (value !== before)

    decl._autoprefixerValues[prefix] = value
  }

  /**
   * Is declaration need to be prefixed
   */
  check(decl) {
    let value = decl.value
    if (!value.includes(this.name)) {
      return false
    }

    return !!value.match(this.regexp())
  }

  /**
   * Return function to fast find prefixed value
   */
  old(prefix) {
    return new OldValue(this.name, prefix + this.name)
  }

  /**
   * Lazy regexp loading
   */
  regexp() {
    return this.regexpCache || (this.regexpCache = utils.regexp(this.name))
  }

  /**
   * Add prefix to values in string
   */
  replace(string, prefix) {
    return string.replace(this.regexp(), `$1${prefix}$2`)
  }

  /**
   * Get value with comments if it was not changed
   */
  value(decl) {
    if (decl.raws.value && decl.raws.value.value === decl.value) {
      return decl.raws.value.raw
    } else {
      return decl.value
    }
  }
}

module.exports = Value


code:
module.exports = {
  prefix(prop) {
    let match = prop.match(/^(-\w+-)/)
    if (match) {
      return match[0]
    }

    return ''
  },

  unprefixed(prop) {
    return prop.replace(/^-\w+-/, '')
  }
}


autoprefixer

description: Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website

keywords: autoprefixer css prefix postcss postcss-plugin

bin: bin/autoprefixer

type: opencollective

type: tidelift

type: github

author: Andrey Sitnik <andrey@sitnik.ru>

license: MIT

repository: postcss/autoprefixer


code:
# Changelog

For changes in version v7.0.0 and up please go to [release](https://github.com/babel/babel-loader/releases)

# Old Changelog

## v6.4.1

### 🐛 Bug Fix

- Fixed reset of BABEL_ENV when options.forceEnv is used (#420) @nikopavlica

## v6.4.0

### 🚀 New Feature

- added metadata passing from babel to webpack, which is currently used by react-intl (#398) @Ognian

## v6.3.2

### 😢 Regression

- `forceEnv` was interfering with regular environment handling

## v6.3.1

### 🐛 Bug Fix

 - The new `forceEnv` options wasn't working as expected (#379) @chrisvasz

## v6.3.0

### 🚀 New Feature

- Add new config option `forceEnv` (#368) @moimael

Allow to override BABEL_ENV/NODE_ENV at loader-level. Useful for isomorphic applications which have   separate babel config for client and server.

### 🐛 Bug Fix

- Update loader-utils dependency to ^0.2.16 to fix compatibility with webpack 2 (#371) @leonaves

### 💅 Polish

- Improve FS caching to do less sync calls which improves performance slightly (#375) @akx

## v6.2.10

Support for webpack 2.2-rc has been added in this release

### 🐛 Bug Fix

- If cache directory not writable, try to fallback to tmpdir before failing

## v6.2.9

### 😢 Regression

Source maps on windows did not work correctly with v6.2.8.
Thanks @josephst

### 🏠 Internal

- Add AppVeyor to run tests on windows @danez
- Fix tests on windows (#343) @danez

## v6.2.8

### 🐛 Bug Fix

- gzipped files should have `.gz` as the extension, not `.gzip` (#326) @bjornstar
- fix options.sourceFileName gennerate bug (#260) @creeperyang

### 📝 Documentation

- Update README docs for cacheDirectory's actual behaviour (#245) @sohkai
- updates docs re: transform-runtime (#197) @gbrassey

### 🏠 Internal

- Use eslint and nyc (#321) @danez
- Adjust travis config (#320) @danez
- Use babel to compile babel-loader (#319) @danez

## v6.2.7

### 😢 Regression

Fallback to `os.tmpdir()` if no cachedir found (#318) (fixes #317) @danez

Fixes an issue with v6.2.6 when using `babel-loader` as a global package.

## v6.2.6

### 🐛 Bug Fix

- Use standard cache dir as default `cacheDirectory` (#301) @fson

Use the common cache directory, `./node_modules/.cache/babel-loader`, as the default cache directory (when the cacheDirectory setting is enabled).

```js
query: {
  cacheDirectory: true
}
```

## v6.2.5

- Don't show the call stack for a Babel error (such as when you have a syntax error)

<img width="415" alt="screenshot 2016-08-15 15 24 37" src="https://cloud.githubusercontent.com/assets/30594/17664401/727ba098-62fc-11e6-9f12-42da0cf47f14.png">

- resolve the .babelrc relative to the file path rather than the cwd (current working directory).

 * fix: more concise formatting for Babel errors (#287) (Andrey Popp)
 * fix(resolve-rc): resolve-rc relative file path (#253) (Luke Page)
 * add babel-core and preset-2015 to dev dependencies (#273) (timse)
 * chore(docs): add issue and pr templates (#280) (Joshua Wiens)
 * chore(docs): fix badge formatting (Joshua Wiens)
 * chore(ci): expand travis testing (#278) (Joshua Wiens)
 * Update README: add env vars to cacheIdentifier (#267) (Dominik Ferber)
 * add npm badge [skip ci] (Henry Zhu)
 * update [skip ci] (Henry Zhu)
 * remove jsx references as well [skip ci] (Henry Zhu)
 * Save the transform to devDependencies (Ray Booysen)
 * Remove 'react' preset (Jake Rios)
 * Removed babel-preset-react from README.md (Ben Stephenson)

## v6.2.4
 * change allowed peer deps (all webpack 2 beta versions)

## v6.2.3
 * change allowed peer deps (2.0.7-beta)

## v6.2.2
  * Update peerDependencies to accept webpack 2 [#208](https://github.com/babel/babel-loader/pull/208)
  * Remove duplicated dependencies

## v6.2.0
  * Pass true filenames [#106](https://github.com/babel/babel-loader/issues/106)
  * Remove babel-core from devDependencies

## v6.1.0

  * Merge [PR #146](https://github.com/babel/babel-loader/pull/146) Set source file name relative to options.sourceRoot
  * Merge [PR #136](https://github.com/babel/babel-loader/pull/136) use container-based infrastructure for faster build
  * Merge [PR #121](https://github.com/babel/babel-loader/pull/121) Make babelrc configurable
  * Merge [PR #113](https://github.com/babel/babel-loader/pull/113) Include BABEL_ENV || NODE_ENV in cacheIdentifier

## v6.0.1

  * Update to babel v6.

## v5.3.1

  * Merge [PR #85](https://github.com/babel/babel-loader/pull/85) - Don't override sourcemap if sourcesContent already exists.

## v5.3.1

  * Merge [PR #82](https://github.com/babel/babel-loader/pull/82) - Fallback global options to empty object to avoid conflicts with object-assign polyfill.

## v5.3.0

  * Merge [PR #79](https://github.com/babel/babel-loader/pull/79) - This should allow babel-loader to work with [enhanced-require](https://github.com/webpack/enhanced-require).

## v5.2.0

  * Include `.babelrc` file into the `cacheIdentifier` if it exists


code:
> This README is for babel-loader v8 + Babel v7
> If you are using legacy Babel v6, see the [7.x branch](https://github.com/babel/babel-loader/tree/7.x) docs

[![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader)
[![codecov](https://codecov.io/gh/babel/babel-loader/branch/main/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader)

Babel Loader

This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).

**Note**: Issues with the output should be reported on the Babel [Issues](https://github.com/babel/babel/issues) tracker.

Install

> webpack `4.x || 5.x` | babel-loader 8.x | babel 7.x

```bash
npm install -D babel-loader @babel/core @babel/preset-env webpack
```

Usage

webpack documentation: [Loaders](https://webpack.js.org/loaders/)

Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:

```javascript
module: {
  rules: [
    {
      test: /\.m?js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ]
        }
      }
    }
  ]
}
```

### Options

See the `babel` [options](https://babeljs.io/docs/en/options).

You can pass options to the loader by using the [`options`](https://webpack.js.org/configuration/module/#ruleoptions--rulequery) property:

```javascript
module: {
  rules: [
    {
      test: /\.m?js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ],
          plugins: ['@babel/plugin-proposal-class-properties']
        }
      }
    }
  ]
}
```

This loader also supports the following loader-specific option:

* `cacheDirectory`: Default `false`. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is set to `true` in options (`{cacheDirectory: true}`), the loader will use the default cache directory in `node_modules/.cache/babel-loader` or fallback to the default OS temporary file directory if no `node_modules` folder could be found in any root directory.

* `cacheIdentifier`: Default is a string composed by the `@babel/core`'s version, the `babel-loader`'s version, the contents of `.babelrc` file if it exists, and the value of the environment variable `BABEL_ENV` with a fallback to the `NODE_ENV` environment variable. This can be set to a custom value to force cache busting if the identifier changes.

* `cacheCompression`: Default `true`. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to `false` -- your project may benefit from this if it transpiles thousands of files.

* `customize`: Default `null`. The path of a module that exports a `custom` callback [like the one that you'd pass to `.custom()`](#customized-loader). Since you already have to make a new file to use this, it is recommended that you instead use `.custom` to create a wrapper loader. Only use this if you _must_ continue using `babel-loader` directly, but still want to customize.

* `metadataSubscribers`: Default `[]`. Takes an array of context function names. E.g. if you passed ['myMetadataPlugin'], you'd assign a subscriber function to `context.myMetadataPlugin` within your webpack plugin's hooks & that function will be called with `metadata`.

## Troubleshooting

### babel-loader is slow!

Make sure you are transforming as few files as possible. Because you are probably matching `/\.m?js$/`, you might be transforming the `node_modules` folder or other unwanted source.

To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above.

You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option. This will cache transformations to the filesystem.

### Some files in my node_modules are not transpiled for IE 11

Although we typically recommend not compiling `node_modules`, you may need to when using libraries that do not support IE 11.

For this, you can either use a combination of `test` and `not`, or [pass a function](https://webpack.js.org/configuration/module/#condition) to your `exclude` option. You can also use negative lookahead regex as suggested [here](https://github.com/webpack/webpack/issues/2031#issuecomment-294706065).

```javascript
{
    test: /\.m?js$/,
    exclude: {
      and: [/node_modules/], // Exclude libraries in node_modules ...
      not: [
        // Except for a few of them that needs to be transpiled because they use modern syntax
        /unfetch/,
        /d3-array|d3-scale/,
        /@hapi[\\/]joi-date/,
      ]
    },
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', { targets: "ie 11" }]
        ]
      }
    }
  }
```

### Babel is injecting helpers into each file and bloating my code!

Babel uses very small helpers for common functions such as `_extend`. By default, this will be added to every file that requires it.

You can instead require the Babel runtime as a separate module to avoid the duplication.

The following configuration disables automatic per-file runtime injection in Babel, requiring `@babel/plugin-transform-runtime` instead and making all helper references use it.

See the [docs](https://babeljs.io/docs/plugins/transform-runtime/) for more information.

**NOTE**: You must run `npm install -D @babel/plugin-transform-runtime` to include this in your project and `@babel/runtime` itself as a dependency with `npm install @babel/runtime`.

```javascript
rules: [
  // the 'transform-runtime' plugin tells Babel to
  // require the runtime instead of inlining it.
  {
    test: /\.m?js$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', { targets: "defaults" }]
        ],
        plugins: ['@babel/plugin-transform-runtime']
      }
    }
  }
]
```

#### **NOTE**: transform-runtime & custom polyfills (e.g. Promise library)

Since [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-runtime) includes a polyfill that includes a custom [regenerator-runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) and [core-js](https://github.com/zloirock/core-js), the following usual shimming method using `webpack.ProvidePlugin` will not work:

```javascript
// ...
        new webpack.ProvidePlugin({
            'Promise': 'bluebird'
        }),
// ...
```

The following approach will not work either:

```javascript
require('@babel/runtime/core-js/promise').default = require('bluebird');

var promise = new Promise;
```

which outputs to (using `runtime`):

```javascript
'use strict';

var _Promise = require('@babel/runtime/core-js/promise')['default'];

require('@babel/runtime/core-js/promise')['default'] = require('bluebird');

var promise = new _Promise();
```

The previous `Promise` library is referenced and used before it is overridden.

One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:

```javascript
// bootstrap.js

require('@babel/runtime/core-js/promise').default = require('bluebird');

// ...

require('./app');
```

### The Node.js API for `babel` has been moved to `babel-core`.

If you receive this message, it means that you have the npm package `babel` installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):
```javascript
  {
    test: /\.m?js$/,
    loader: 'babel',
  }
```

webpack then tries to load the `babel` package instead of the `babel-loader`.

To fix this, you should uninstall the npm package `babel`, as it is deprecated in Babel v6. (Instead, install `@babel/cli` or `@babel/core`.)
In the case one of your dependencies is installing `babel` and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:
```javascript
  {
    test: /\.m?js$/,
    loader: 'babel-loader',
  }
```

### Exclude libraries that should not be transpiled

`core-js` and `webpack/buildin` will cause errors if they are transpiled by Babel.

You will need to exclude them form `babel-loader`.

```js
{
  "loader": "babel-loader",
  "options": {
    "exclude": [
      // \\ for Windows, / for macOS and Linux
      /node_modules[\\/]core-js/,
      /node_modules[\\/]webpack[\\/]buildin/,
    ],
    "presets": [
      "@babel/preset-env"
    ]
  }
}
```

### Top level function (IIFE) is still arrow (on Webpack 5)

That function is injected by Webpack itself _after_ running `babel-loader`. By default Webpack asumes that your target environment supports some ES2015 features, but you can overwrite this behavior using the `output.environment` Webpack option ([documentation](https://webpack.js.org/configuration/output/#outputenvironment)).

To avoid the top-level arrow function, you can use `output.environment.arrowFunction`:

```js
// webpack.config.js
module.exports = {
  // ...
  output: {
    // ...
    environment: {
      // ...
      arrowFunction: false, // <-- this line does the trick
    },
  },
};
```

## Customize config based on webpack target

Webpack supports bundling multiple [targets](https://webpack.js.org/concepts/targets/). For cases where you may want different Babel configurations for each target (like `web` _and_ `node`), this loader provides a `target` property via Babel's [caller](https://babeljs.io/docs/en/config-files#apicallercb) API.

For example, to change the environment targets passed to `@babel/preset-env` based on the webpack target:

```javascript
// babel.config.js

module.exports = api => {
  return {
    plugins: [
      "@babel/plugin-proposal-nullish-coalescing-operator",
      "@babel/plugin-proposal-optional-chaining"
    ],
    presets: [
      [
        "@babel/preset-env",
        {
          useBuiltIns: "entry",
          // caller.target will be the same as the target option from webpack
          targets: api.caller(caller => caller && caller.target === "node")
            ? { node: "current" }
            : { chrome: "58", ie: "11" }
        }
      ]
    ]
  }
}
```

## Customized Loader

`babel-loader` exposes a loader-builder utility that allows users to add custom handling
of Babel's configuration for each file that it processes.

`.custom` accepts a callback that will be called with the loader's instance of
`babel` so that tooling can ensure that it using exactly the same `@babel/core`
instance as the loader itself.

In cases where you want to customize without actually having a file to call `.custom`, you
may also pass the `customize` option with a string pointing at a file that exports
your `custom` callback function.

### Example

```js
// Export from "./my-custom-loader.js" or whatever you want.
module.exports = require("babel-loader").custom(babel => {
  function myPlugin() {
    return {
      visitor: {},
    };
  }

  return {
    // Passed the loader options.
    customOptions({ opt1, opt2, ...loader }) {
      return {
        // Pull out any custom options that the loader might have.
        custom: { opt1, opt2 },

        // Pass the options back with the two custom options removed.
        loader,
      };
    },

    // Passed Babel's 'PartialConfig' object.
    config(cfg) {
      if (cfg.hasFilesystemConfig()) {
        // Use the normal config
        return cfg.options;
      }

      return {
        ...cfg.options,
        plugins: [
          ...(cfg.options.plugins || []),

          // Include a custom plugin in the options.
          myPlugin,
        ],
      };
    },

    result(result) {
      return {
        ...result,
        code: result.code + "\n// Generated by some custom loader",
      };
    },
  };
});
```

```js
// And in your Webpack config
module.exports = {
  // ..
  module: {
    rules: [{
      // ...
      loader: path.join(__dirname, 'my-custom-loader.js'),
      // ...
    }]
  }
};
```

### `customOptions(options: Object): { custom: Object, loader: Object }`

Given the loader's options, split custom options out of `babel-loader`'s
options.

### `config(cfg: PartialConfig): Object`

Given Babel's `PartialConfig` object, return the `options` object that should
be passed to `babel.transform`.

### `result(result: Result): Result`

Given Babel's result object, allow loaders to make additional tweaks to it.

## License
[MIT](https://couto.mit-license.org/)


code:
"use strict";

const STRIP_FILENAME_RE = /^[^:]+: /;
const format = err => {
  if (err instanceof SyntaxError) {
    err.name = "SyntaxError";
    err.message = err.message.replace(STRIP_FILENAME_RE, "");
    err.hideStack = true;
  } else if (err instanceof TypeError) {
    err.name = null;
    err.message = err.message.replace(STRIP_FILENAME_RE, "");
    err.hideStack = true;
  }
  return err;
};
class LoaderError extends Error {
  constructor(err) {
    super();
    const {
      name,
      message,
      codeFrame,
      hideStack
    } = format(err);
    this.name = "BabelLoaderError";
    this.message = `${name ? `${name}: ` : ""}${message}\n\n${codeFrame}\n`;
    this.hideStack = hideStack;
    Error.captureStackTrace(this, this.constructor);
  }
}
module.exports = LoaderError;


code:
"use strict";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
/**
 * Filesystem Cache
 *
 * Given a file and a transform function, cache the result into files
 * or retrieve the previously cached files if the given file is already known.
 *
 * @see https://github.com/babel/babel-loader/issues/34
 * @see https://github.com/babel/babel-loader/pull/41
 */
const fs = require("fs");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
const crypto = require("crypto");
const findCacheDir = require("find-cache-dir");
const {
  promisify
} = require("util");
const transform = require("./transform");
// Lazily instantiated when needed
let defaultCacheDirectory = null;
let hashType = "sha256";
// use md5 hashing if sha256 is not available
try {
  crypto.createHash(hashType);
} catch (err) {
  hashType = "md5";
}
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const gunzip = promisify(zlib.gunzip);
const gzip = promisify(zlib.gzip);
const makeDir = require("make-dir");

/**
 * Read the contents from the compressed file.
 *
 * @async
 * @params {String} filename
 * @params {Boolean} compress
 */
const read = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator(function* (filename, compress) {
    const data = yield readFile(filename + (compress ? ".gz" : ""));
    const content = compress ? yield gunzip(data) : data;
    return JSON.parse(content.toString());
  });
  return function read(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

/**
 * Write contents into a compressed file.
 *
 * @async
 * @params {String} filename
 * @params {Boolean} compress
 * @params {String} result
 */
const write = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator(function* (filename, compress, result) {
    const content = JSON.stringify(result);
    const data = compress ? yield gzip(content) : content;
    return yield writeFile(filename + (compress ? ".gz" : ""), data);
  });
  return function write(_x3, _x4, _x5) {
    return _ref2.apply(this, arguments);
  };
}();

/**
 * Build the filename for the cached file
 *
 * @params {String} source  File source code
 * @params {Object} options Options used
 *
 * @return {String}
 */
const filename = function (source, identifier, options) {
  const hash = crypto.createHash(hashType);
  const contents = JSON.stringify({
    source,
    options,
    identifier
  });
  hash.update(contents);
  return hash.digest("hex") + ".json";
};

/**
 * Handle the cache
 *
 * @params {String} directory
 * @params {Object} params
 */
const handleCache = /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator(function* (directory, params) {
    const {
      source,
      options = {},
      cacheIdentifier,
      cacheDirectory,
      cacheCompression
    } = params;
    const file = path.join(directory, filename(source, cacheIdentifier, options));
    try {
      // No errors mean that the file was previously cached
      // we just need to return it
      return yield read(file, cacheCompression);
    } catch (err) {}
    const fallback = typeof cacheDirectory !== "string" && directory !== os.tmpdir();

    // Make sure the directory exists.
    try {
      yield makeDir(directory);
    } catch (err) {
      if (fallback) {
        return handleCache(os.tmpdir(), params);
      }
      throw err;
    }

    // Otherwise just transform the file
    // return it to the user asap and write it in cache
    const result = yield transform(source, options);

    // Do not cache if there are external dependencies,
    // since they might change and we cannot control it.
    if (!result.externalDependencies.length) {
      try {
        yield write(file, cacheCompression, result);
      } catch (err) {
        if (fallback) {
          // Fallback to tmpdir if node_modules folder not writable
          return handleCache(os.tmpdir(), params);
        }
        throw err;
      }
    }
    return result;
  });
  return function handleCache(_x6, _x7) {
    return _ref3.apply(this, arguments);
  };
}();

/**
 * Retrieve file from cache, or create a new one for future reads
 *
 * @async
 * @param  {Object}   params
 * @param  {String}   params.cacheDirectory   Directory to store cached files
 * @param  {String}   params.cacheIdentifier  Unique identifier to bust cache
 * @param  {Boolean}  params.cacheCompression Whether compressing cached files
 * @param  {String}   params.source   Original contents of the file to be cached
 * @param  {Object}   params.options  Options to be given to the transform fn
 *
 * @example
 *
 *   const result = await cache({
 *     cacheDirectory: '.tmp/cache',
 *     cacheIdentifier: 'babel-loader-cachefile',
 *     cacheCompression: false,
 *     source: *source code from file*,
 *     options: {
 *       experimental: true,
 *       runtime: true
 *     },
 *   });
 */

module.exports = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator(function* (params) {
    let directory;
    if (typeof params.cacheDirectory === "string") {
      directory = params.cacheDirectory;
    } else {
      if (defaultCacheDirectory === null) {
        defaultCacheDirectory = findCacheDir({
          name: "babel-loader"
        }) || os.tmpdir();
      }
      directory = defaultCacheDirectory;
    }
    return yield handleCache(directory, params);
  });
  return function (_x8) {
    return _ref4.apply(this, arguments);
  };
}();


code:
"use strict";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
let babel;
try {
  babel = require("@babel/core");
} catch (err) {
  if (err.code === "MODULE_NOT_FOUND") {
    err.message += "\n babel-loader@8 requires Babel 7.x (the package '@babel/core'). " + "If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.";
  }
  throw err;
}

// Since we've got the reverse bridge package at @babel/core@6.x, give
// people useful feedback if they try to use it alongside babel-loader.
if (/^6\./.test(babel.version)) {
  throw new Error("\n babel-loader@8 will not work with the '@babel/core@6' bridge package. " + "If you want to use Babel 6.x, install 'babel-loader@7'.");
}
const {
  version
} = require("../package.json");
const cache = require("./cache");
const transform = require("./transform");
const injectCaller = require("./injectCaller");
const schema = require("./schema");
const {
  isAbsolute
} = require("path");
const loaderUtils = require("loader-utils");
const validateOptions = require("schema-utils");
function subscribe(subscriber, metadata, context) {
  if (context[subscriber]) {
    context[subscriber](metadata);
  }
}
module.exports = makeLoader();
module.exports.custom = makeLoader;
function makeLoader(callback) {
  const overrides = callback ? callback(babel) : undefined;
  return function (source, inputSourceMap) {
    // Make the loader async
    const callback = this.async();
    loader.call(this, source, inputSourceMap, overrides).then(args => callback(null, ...args), err => callback(err));
  };
}
function loader(_x, _x2, _x3) {
  return _loader.apply(this, arguments);
}
function _loader() {
  _loader = _asyncToGenerator(function* (source, inputSourceMap, overrides) {
    const filename = this.resourcePath;
    let loaderOptions = loaderUtils.getOptions(this);
    validateOptions(schema, loaderOptions, {
      name: "Babel loader"
    });
    if (loaderOptions.customize != null) {
      if (typeof loaderOptions.customize !== "string") {
        throw new Error("Customized loaders must be implemented as standalone modules.");
      }
      if (!isAbsolute(loaderOptions.customize)) {
        throw new Error("Customized loaders must be passed as absolute paths, since " + "babel-loader has no way to know what they would be relative to.");
      }
      if (overrides) {
        throw new Error("babel-loader's 'customize' option is not available when already " + "using a customized babel-loader wrapper.");
      }
      let override = require(loaderOptions.customize);
      if (override.__esModule) override = override.default;
      if (typeof override !== "function") {
        throw new Error("Custom overrides must be functions.");
      }
      overrides = override(babel);
    }
    let customOptions;
    if (overrides && overrides.customOptions) {
      const result = yield overrides.customOptions.call(this, loaderOptions, {
        source,
        map: inputSourceMap
      });
      customOptions = result.custom;
      loaderOptions = result.loader;
    }

    // Deprecation handling
    if ("forceEnv" in loaderOptions) {
      console.warn("The option `forceEnv` has been removed in favor of `envName` in Babel 7.");
    }
    if (typeof loaderOptions.babelrc === "string") {
      console.warn("The option `babelrc` should not be set to a string anymore in the babel-loader config. " + "Please update your configuration and set `babelrc` to true or false.\n" + "If you want to specify a specific babel config file to inherit config from " + "please use the `extends` option.\nFor more information about this options see " + "https://babeljs.io/docs/core-packages/#options");
    }

    // Standardize on 'sourceMaps' as the key passed through to Webpack, so that
    // users may safely use either one alongside our default use of
    // 'this.sourceMap' below without getting error about conflicting aliases.
    if (Object.prototype.hasOwnProperty.call(loaderOptions, "sourceMap") && !Object.prototype.hasOwnProperty.call(loaderOptions, "sourceMaps")) {
      loaderOptions = Object.assign({}, loaderOptions, {
        sourceMaps: loaderOptions.sourceMap
      });
      delete loaderOptions.sourceMap;
    }
    const programmaticOptions = Object.assign({}, loaderOptions, {
      filename,
      inputSourceMap: inputSourceMap || loaderOptions.inputSourceMap,
      // Set the default sourcemap behavior based on Webpack's mapping flag,
      // but allow users to override if they want.
      sourceMaps: loaderOptions.sourceMaps === undefined ? this.sourceMap : loaderOptions.sourceMaps,
      // Ensure that Webpack will get a full absolute path in the sourcemap
      // so that it can properly map the module back to its internal cached
      // modules.
      sourceFileName: filename
    });
    // Remove loader related options
    delete programmaticOptions.customize;
    delete programmaticOptions.cacheDirectory;
    delete programmaticOptions.cacheIdentifier;
    delete programmaticOptions.cacheCompression;
    delete programmaticOptions.metadataSubscribers;
    if (!babel.loadPartialConfig) {
      throw new Error(`babel-loader ^8.0.0-beta.3 requires @babel/core@7.0.0-beta.41, but ` + `you appear to be using "${babel.version}". Either update your ` + `@babel/core version, or pin you babel-loader version to 8.0.0-beta.2`);
    }

    // babel.loadPartialConfigAsync is available in v7.8.0+
    const {
      loadPartialConfigAsync = babel.loadPartialConfig
    } = babel;
    const config = yield loadPartialConfigAsync(injectCaller(programmaticOptions, this.target));
    if (config) {
      let options = config.options;
      if (overrides && overrides.config) {
        options = yield overrides.config.call(this, config, {
          source,
          map: inputSourceMap,
          customOptions
        });
      }
      if (options.sourceMaps === "inline") {
        // Babel has this weird behavior where if you set "inline", we
        // inline the sourcemap, and set 'result.map = null'. This results
        // in bad behavior from Babel since the maps get put into the code,
        // which Webpack does not expect, and because the map we return to
        // Webpack is null, which is also bad. To avoid that, we override the
        // behavior here so "inline" just behaves like 'true'.
        options.sourceMaps = true;
      }
      const {
        cacheDirectory = null,
        cacheIdentifier = JSON.stringify({
          options,
          "@babel/core": transform.version,
          "@babel/loader": version
        }),
        cacheCompression = true,
        metadataSubscribers = []
      } = loaderOptions;
      let result;
      if (cacheDirectory) {
        result = yield cache({
          source,
          options,
          transform,
          cacheDirectory,
          cacheIdentifier,
          cacheCompression
        });
      } else {
        result = yield transform(source, options);
      }

      // Availabe since Babel 7.12
      // https://github.com/babel/babel/pull/11907
      if (config.files) {
        config.files.forEach(configFile => this.addDependency(configFile));
      } else {
        // .babelrc.json
        if (typeof config.babelrc === "string") {
          this.addDependency(config.babelrc);
        }
        // babel.config.js
        if (config.config) {
          this.addDependency(config.config);
        }
      }
      if (result) {
        if (overrides && overrides.result) {
          result = yield overrides.result.call(this, result, {
            source,
            map: inputSourceMap,
            customOptions,
            config,
            options
          });
        }
        const {
          code,
          map,
          metadata,
          externalDependencies
        } = result;
        externalDependencies == null ? void 0 : externalDependencies.forEach(dep => this.addDependency(dep));
        metadataSubscribers.forEach(subscriber => {
          subscribe(subscriber, metadata, this);
        });
        return [code, map];
      }
    }

    // If the file was ignored, pass through the original content.
    return [source, inputSourceMap];
  });
  return _loader.apply(this, arguments);
}


code:
"use strict";

const babel = require("@babel/core");
module.exports = function injectCaller(opts, target) {
  if (!supportsCallerOption()) return opts;
  return Object.assign({}, opts, {
    caller: Object.assign({
      name: "babel-loader",
      // Provide plugins with insight into webpack target.
      // https://github.com/babel/babel-loader/issues/787
      target,
      // Webpack >= 2 supports ESM and dynamic import.
      supportsStaticESM: true,
      supportsDynamicImport: true,
      // Webpack 5 supports TLA behind a flag. We enable it by default
      // for Babel, and then webpack will throw an error if the experimental
      // flag isn't enabled.
      supportsTopLevelAwait: true
    }, opts.caller)
  });
};

// TODO: We can remove this eventually, I'm just adding it so that people have
// a little time to migrate to the newer RCs of @babel/core without getting
// hard-to-diagnose errors about unknown 'caller' options.
let supportsCallerOptionFlag = undefined;
function supportsCallerOption() {
  if (supportsCallerOptionFlag === undefined) {
    try {
      // Rather than try to match the Babel version, we just see if it throws
      // when passed a 'caller' flag, and use that to decide if it is supported.
      babel.loadPartialConfig({
        caller: undefined,
        babelrc: false,
        configFile: false
      });
      supportsCallerOptionFlag = true;
    } catch (err) {
      supportsCallerOptionFlag = false;
    }
  }
  return supportsCallerOptionFlag;
}


type: object

type: boolean

type: string


code:
"use strict";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
const babel = require("@babel/core");
const {
  promisify
} = require("util");
const LoaderError = require("./Error");
const transform = promisify(babel.transform);
module.exports = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator(function* (source, options) {
    let result;
    try {
      result = yield transform(source, options);
    } catch (err) {
      throw err.message && err.codeFrame ? new LoaderError(err) : err;
    }
    if (!result) return null;

    // We don't return the full result here because some entries are not
    // really serializable. For a full list of properties see here:
    // https://github.com/babel/babel/blob/main/packages/babel-core/src/transformation/index.js
    // For discussion on this topic see here:
    // https://github.com/babel/babel-loader/pull/629
    const {
      ast,
      code,
      map,
      metadata,
      sourceType,
      externalDependencies
    } = result;
    if (map && (!map.sourcesContent || !map.sourcesContent.length)) {
      map.sourcesContent = [source];
    }
    return {
      ast,
      code,
      map,
      metadata,
      sourceType,
      // Convert it from a Set to an Array to make it JSON-serializable.
      externalDependencies: Array.from(externalDependencies || [])
    };
  });
  return function (_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();
module.exports.version = babel.version;


code:
# loader-utils

## Methods

### `getOptions`

Recommended way to retrieve the options of a loader invocation:

```javascript
// inside your loader
const options = loaderUtils.getOptions(this);
```

1. If `this.query` is a string:
	- Tries to parse the query string and returns a new object
	- Throws if it's not a valid query string
2. If `this.query` is object-like, it just returns `this.query`
3. In any other case, it just returns `null`

**Please note:** The returned `options` object is *read-only*. It may be re-used across multiple invocations.
If you pass it on to another library, make sure to make a *deep copy* of it:

```javascript
const options = Object.assign(
	{},
	defaultOptions,
	loaderUtils.getOptions(this) // it is safe to pass null to Object.assign()
);
// don't forget nested objects or arrays
options.obj = Object.assign({}, options.obj);
options.arr = options.arr.slice();
someLibrary(options);
```

[clone](https://www.npmjs.com/package/clone) is a good library to make a deep copy of the options.

#### Options as query strings

If the loader options have been passed as loader query string (`loader?some&params`), the string is parsed by using [`parseQuery`](#parsequery).

### `parseQuery`

Parses a passed string (e.g. `loaderContext.resourceQuery`) as a query string, and returns an object.

``` javascript
const params = loaderUtils.parseQuery(this.resourceQuery); // resource: `file?param1=foo`
if (params.param1 === "foo") {
	// do something
}
```

The string is parsed like this:

``` text
                             -> Error
?                            -> {}
?flag                        -> { flag: true }
?+flag                       -> { flag: true }
?-flag                       -> { flag: false }
?xyz=test                    -> { xyz: "test" }
?xyz=1                       -> { xyz: "1" } // numbers are NOT parsed
?xyz[]=a                     -> { xyz: ["a"] }
?flag1&flag2                 -> { flag1: true, flag2: true }
?+flag1,-flag2               -> { flag1: true, flag2: false }
?xyz[]=a,xyz[]=b             -> { xyz: ["a", "b"] }
?a%2C%26b=c%2C%26d           -> { "a,&b": "c,&d" }
?{data:{a:1},isJSON5:true}   -> { data: { a: 1 }, isJSON5: true }
```

### `stringifyRequest`

Turns a request into a string that can be used inside `require()` or `import` while avoiding absolute paths.
Use it instead of `JSON.stringify(...)` if you're generating code inside a loader.

**Why is this necessary?** Since webpack calculates the hash before module paths are translated into module ids, we must avoid absolute paths to ensure
consistent hashes across different compilations.

This function:

- resolves absolute requests into relative requests if the request and the module are on the same hard drive
- replaces `\` with `/` if the request and the module are on the same hard drive
- won't change the path at all if the request and the module are on different hard drives
- applies `JSON.stringify` to the result

```javascript
loaderUtils.stringifyRequest(this, "./test.js");
// "\"./test.js\""

loaderUtils.stringifyRequest(this, ".\\test.js");
// "\"./test.js\""

loaderUtils.stringifyRequest(this, "test");
// "\"test\""

loaderUtils.stringifyRequest(this, "test/lib/index.js");
// "\"test/lib/index.js\""

loaderUtils.stringifyRequest(this, "otherLoader?andConfig!test?someConfig");
// "\"otherLoader?andConfig!test?someConfig\""

loaderUtils.stringifyRequest(this, require.resolve("test"));
// "\"../node_modules/some-loader/lib/test.js\""

loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
// "\"../../test.js\"" (on Windows, in case the module and the request are on the same drive)

loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
// "\"C:\\module\\test.js\"" (on Windows, in case the module and the request are on different drives)

loaderUtils.stringifyRequest(this, "\\\\network-drive\\test.js");
// "\"\\\\network-drive\\\\test.js\"" (on Windows, in case the module and the request are on different drives)
```

### `urlToRequest`

Converts some resource URL to a webpack module request.

> i Before call `urlToRequest` you need call `isUrlRequest` to ensure it is requestable url

```javascript
const url = "path/to/module.js";

if (loaderUtils.isUrlRequest(url)) {
  // Logic for requestable url
  const request = loaderUtils.urlToRequest(url);
} else {
  // Logic for not requestable url
}
```

Simple example:

```javascript
const url = "path/to/module.js";
const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
```

#### Module URLs

Any URL containing a `~` will be interpreted as a module request. Anything after the `~` will be considered the request path.

```javascript
const url = "~path/to/module.js";
const request = loaderUtils.urlToRequest(url); // "path/to/module.js"
```

#### Root-relative URLs

URLs that are root-relative (start with `/`) can be resolved relative to some arbitrary path by using the `root` parameter:

```javascript
const url = "/path/to/module.js";
const root = "./root";
const request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js"
```

To convert a root-relative URL into a module URL, specify a `root` value that starts with `~`:

```javascript
const url = "/path/to/module.js";
const root = "~";
const request = loaderUtils.urlToRequest(url, root); // "path/to/module.js"
```

### `interpolateName`

Interpolates a filename template using multiple placeholders and/or a regular expression.
The template and regular expression are set as query params called `name` and `regExp` on the current loader's context.

```javascript
const interpolatedName = loaderUtils.interpolateName(loaderContext, name, options);
```

The following tokens are replaced in the `name` parameter:

* `[ext]` the extension of the resource
* `[name]` the basename of the resource
* `[path]` the path of the resource relative to the `context` query parameter or option.
* `[folder]` the folder the resource is in
* `[query]` the queryof the resource, i.e. `?foo=bar`
* `[emoji]` a random emoji representation of `options.content`
* `[emoji:<length>]` same as above, but with a customizable number of emojis
* `[contenthash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md4 hash)
* `[<hashType>:contenthash:<digestType>:<length>]` optionally one can configure
  * other `hashType`s, i. e. `sha1`, `md4`, `md5`, `sha256`, `sha512`
  * other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
  * and `length` the length in chars
* `[hash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md4 hash)
* `[<hashType>:hash:<digestType>:<length>]` optionally one can configure
  * other `hashType`s, i. e. `sha1`, `md4`, `md5`, `sha256`, `sha512`
  * other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
  * and `length` the length in chars
* `[N]` the N-th match obtained from matching the current file name against `options.regExp`

In loader context `[hash]` and `[contenthash]` are the same, but we recommend using `[contenthash]` for avoid misleading.

Examples

``` javascript
// loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext]", { content: ... });
// => js/9473fdd0d880a43c21b7778d34872157.script.js

// loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
// loaderContext.resourceQuery = "?foo=bar"
loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext][query]", { content: ... });
// => js/9473fdd0d880a43c21b7778d34872157.script.js?foo=bar

// loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
loaderUtils.interpolateName(loaderContext, "js/[contenthash].script.[ext]", { content: ... });
// => js/9473fdd0d880a43c21b7778d34872157.script.js

// loaderContext.resourcePath = "/absolute/path/to/app/page.html"
loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... });
// => html-9473fd.html

// loaderContext.resourcePath = "/absolute/path/to/app/flash.txt"
loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... });
// => c31e9820c001c9c4a86bce33ce43b679

// loaderContext.resourcePath = "/absolute/path/to/app/img/image.gif"
loaderUtils.interpolateName(loaderContext, "[emoji]", { content: ... });
// => 👍

// loaderContext.resourcePath = "/absolute/path/to/app/img/image.gif"
loaderUtils.interpolateName(loaderContext, "[emoji:4]", { content: ... });
// => 🙍🏢📤🐝

// loaderContext.resourcePath = "/absolute/path/to/app/img/image.png"
loaderUtils.interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: ... });
// => 2BKDTjl.png
// use sha512 hash instead of md4 and with only 7 chars of base64

// loaderContext.resourcePath = "/absolute/path/to/app/img/myself.png"
// loaderContext.query.name =
loaderUtils.interpolateName(loaderContext, "picture.png");
// => picture.png

// loaderContext.resourcePath = "/absolute/path/to/app/dir/file.png"
loaderUtils.interpolateName(loaderContext, "[path][name].[ext]?[hash]", { content: ... });
// => /app/dir/file.png?9473fdd0d880a43c21b7778d34872157

// loaderContext.resourcePath = "/absolute/path/to/app/js/page-home.js"
loaderUtils.interpolateName(loaderContext, "script-[1].[ext]", { regExp: "page-(.*)\\.js", content: ... });
// => script-home.js

// loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
// loaderContext.resourceQuery = "?foo=bar"
loaderUtils.interpolateName(
  loaderContext,
  (resourcePath, resourceQuery) => {
    // resourcePath - `/app/js/javascript.js`
    // resourceQuery - `?foo=bar`

    return "js/[hash].script.[ext]";
  },
  { content: ... }
);
// => js/9473fdd0d880a43c21b7778d34872157.script.js
```

### `getHashDigest`

``` javascript
const digestString = loaderUtils.getHashDigest(buffer, hashType, digestType, maxLength);
```

* `buffer` the content that should be hashed
* `hashType` one of `sha1`, `md4`, `md5`, `sha256`, `sha512` or any other node.js supported hash type
* `digestType` one of `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
* `maxLength` the maximum length in chars

## License

MIT (http://www.opensource.org/licenses/mit-license.php)


code:
'use strict';

function getCurrentRequest(loaderContext) {
  if (loaderContext.currentRequest) {
    return loaderContext.currentRequest;
  }

  const request = loaderContext.loaders
    .slice(loaderContext.loaderIndex)
    .map((obj) => obj.request)
    .concat([loaderContext.resource]);

  return request.join('!');
}

module.exports = getCurrentRequest;


code:
'use strict';

const baseEncodeTables = {
  26: 'abcdefghijklmnopqrstuvwxyz',
  32: '123456789abcdefghjkmnpqrstuvwxyz', // no 0lio
  36: '0123456789abcdefghijklmnopqrstuvwxyz',
  49: 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', // no lIO
  52: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  58: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', // no 0lIO
  62: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  64: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_',
};

function encodeBufferToBase(buffer, base) {
  const encodeTable = baseEncodeTables[base];
  if (!encodeTable) {
    throw new Error('Unknown encoding base' + base);
  }

  const readLength = buffer.length;
  const Big = require('big.js');

  Big.RM = Big.DP = 0;
  let b = new Big(0);

  for (let i = readLength - 1; i >= 0; i--) {
    b = b.times(256).plus(buffer[i]);
  }

  let output = '';
  while (b.gt(0)) {
    output = encodeTable[b.mod(base)] + output;
    b = b.div(base);
  }

  Big.DP = 20;
  Big.RM = 1;

  return output;
}

let createMd4 = undefined;
let BatchedHash = undefined;

function getHashDigest(buffer, hashType, digestType, maxLength) {
  hashType = hashType || 'md4';
  maxLength = maxLength || 9999;

  let hash;

  try {
    hash = require('crypto').createHash(hashType);
  } catch (error) {
    if (error.code === 'ERR_OSSL_EVP_UNSUPPORTED' && hashType === 'md4') {
      if (createMd4 === undefined) {
        createMd4 = require('./hash/md4');

        if (BatchedHash === undefined) {
          BatchedHash = require('./hash/BatchedHash');
        }
      }

      hash = new BatchedHash(createMd4());
    }

    if (!hash) {
      throw error;
    }
  }

  hash.update(buffer);

  if (
    digestType === 'base26' ||
    digestType === 'base32' ||
    digestType === 'base36' ||
    digestType === 'base49' ||
    digestType === 'base52' ||
    digestType === 'base58' ||
    digestType === 'base62'
  ) {
    return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(
      0,
      maxLength
    );
  } else {
    return hash.digest(digestType || 'hex').substr(0, maxLength);
  }
}

module.exports = getHashDigest;


code:
'use strict';

const parseQuery = require('./parseQuery');

function getOptions(loaderContext) {
  const query = loaderContext.query;

  if (typeof query === 'string' && query !== '') {
    return parseQuery(loaderContext.query);
  }

  if (!query || typeof query !== 'object') {
    // Not object-like queries are not supported.
    return {};
  }

  return query;
}

module.exports = getOptions;


code:
'use strict';

function getRemainingRequest(loaderContext) {
  if (loaderContext.remainingRequest) {
    return loaderContext.remainingRequest;
  }

  const request = loaderContext.loaders
    .slice(loaderContext.loaderIndex + 1)
    .map((obj) => obj.request)
    .concat([loaderContext.resource]);

  return request.join('!');
}

module.exports = getRemainingRequest;


code:
const MAX_SHORT_STRING = require('./wasm-hash').MAX_SHORT_STRING;

class BatchedHash {
  constructor(hash) {
    this.string = undefined;
    this.encoding = undefined;
    this.hash = hash;
  }

  /**
   * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
   * @param {string|Buffer} data data
   * @param {string=} inputEncoding data encoding
   * @returns {this} updated hash
   */
  update(data, inputEncoding) {
    if (this.string !== undefined) {
      if (
        typeof data === 'string' &&
        inputEncoding === this.encoding &&
        this.string.length + data.length < MAX_SHORT_STRING
      ) {
        this.string += data;

        return this;
      }

      this.hash.update(this.string, this.encoding);
      this.string = undefined;
    }

    if (typeof data === 'string') {
      if (
        data.length < MAX_SHORT_STRING &&
        // base64 encoding is not valid since it may contain padding chars
        (!inputEncoding || !inputEncoding.startsWith('ba'))
      ) {
        this.string = data;
        this.encoding = inputEncoding;
      } else {
        this.hash.update(data, inputEncoding);
      }
    } else {
      this.hash.update(data);
    }

    return this;
  }

  /**
   * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
   * @param {string=} encoding encoding of the return value
   * @returns {string|Buffer} digest
   */
  digest(encoding) {
    if (this.string !== undefined) {
      this.hash.update(this.string, this.encoding);
    }

    return this.hash.digest(encoding);
  }
}

module.exports = BatchedHash;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

'use strict';

// 65536 is the size of a wasm memory page
// 64 is the maximum chunk size for every possible wasm hash implementation
// 4 is the maximum number of bytes per char for string encoding (max is utf-8)
// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;

class WasmHash {
  /**
   * @param {WebAssembly.Instance} instance wasm instance
   * @param {WebAssembly.Instance[]} instancesPool pool of instances
   * @param {number} chunkSize size of data chunks passed to wasm
   * @param {number} digestSize size of digest returned by wasm
   */
  constructor(instance, instancesPool, chunkSize, digestSize) {
    const exports = /** @type {any} */ (instance.exports);

    exports.init();

    this.exports = exports;
    this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
    this.buffered = 0;
    this.instancesPool = instancesPool;
    this.chunkSize = chunkSize;
    this.digestSize = digestSize;
  }

  reset() {
    this.buffered = 0;
    this.exports.init();
  }

  /**
   * @param {Buffer | string} data data
   * @param {BufferEncoding=} encoding encoding
   * @returns {this} itself
   */
  update(data, encoding) {
    if (typeof data === 'string') {
      while (data.length > MAX_SHORT_STRING) {
        this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
        data = data.slice(MAX_SHORT_STRING);
      }

      this._updateWithShortString(data, encoding);

      return this;
    }

    this._updateWithBuffer(data);

    return this;
  }

  /**
   * @param {string} data data
   * @param {BufferEncoding=} encoding encoding
   * @returns {void}
   */
  _updateWithShortString(data, encoding) {
    const { exports, buffered, mem, chunkSize } = this;

    let endPos;

    if (data.length < 70) {
      if (!encoding || encoding === 'utf-8' || encoding === 'utf8') {
        endPos = buffered;
        for (let i = 0; i < data.length; i++) {
          const cc = data.charCodeAt(i);

          if (cc < 0x80) {
            mem[endPos++] = cc;
          } else if (cc < 0x800) {
            mem[endPos] = (cc >> 6) | 0xc0;
            mem[endPos + 1] = (cc & 0x3f) | 0x80;
            endPos += 2;
          } else {
            // bail-out for weird chars
            endPos += mem.write(data.slice(i), endPos, encoding);
            break;
          }
        }
      } else if (encoding === 'latin1') {
        endPos = buffered;

        for (let i = 0; i < data.length; i++) {
          const cc = data.charCodeAt(i);

          mem[endPos++] = cc;
        }
      } else {
        endPos = buffered + mem.write(data, buffered, encoding);
      }
    } else {
      endPos = buffered + mem.write(data, buffered, encoding);
    }

    if (endPos < chunkSize) {
      this.buffered = endPos;
    } else {
      const l = endPos & ~(this.chunkSize - 1);

      exports.update(l);

      const newBuffered = endPos - l;

      this.buffered = newBuffered;

      if (newBuffered > 0) {
        mem.copyWithin(0, l, endPos);
      }
    }
  }

  /**
   * @param {Buffer} data data
   * @returns {void}
   */
  _updateWithBuffer(data) {
    const { exports, buffered, mem } = this;
    const length = data.length;

    if (buffered + length < this.chunkSize) {
      data.copy(mem, buffered, 0, length);

      this.buffered += length;
    } else {
      const l = (buffered + length) & ~(this.chunkSize - 1);

      if (l > 65536) {
        let i = 65536 - buffered;

        data.copy(mem, buffered, 0, i);
        exports.update(65536);

        const stop = l - buffered - 65536;

        while (i < stop) {
          data.copy(mem, 0, i, i + 65536);
          exports.update(65536);
          i += 65536;
        }

        data.copy(mem, 0, i, l - buffered);

        exports.update(l - buffered - i);
      } else {
        data.copy(mem, buffered, 0, l - buffered);

        exports.update(l);
      }

      const newBuffered = length + buffered - l;

      this.buffered = newBuffered;

      if (newBuffered > 0) {
        data.copy(mem, 0, length - newBuffered, length);
      }
    }
  }

  digest(type) {
    const { exports, buffered, mem, digestSize } = this;

    exports.final(buffered);

    this.instancesPool.push(this);

    const hex = mem.toString('latin1', 0, digestSize);

    if (type === 'hex') {
      return hex;
    }

    if (type === 'binary' || !type) {
      return Buffer.from(hex, 'hex');
    }

    return Buffer.from(hex, 'hex').toString(type);
  }
}

const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  if (instancesPool.length > 0) {
    const old = instancesPool.pop();

    old.reset();

    return old;
  } else {
    return new WasmHash(
      new WebAssembly.Instance(wasmModule),
      instancesPool,
      chunkSize,
      digestSize
    );
  }
};

module.exports = create;
module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;


code:
'use strict';

const getOptions = require('./getOptions');
const parseQuery = require('./parseQuery');
const stringifyRequest = require('./stringifyRequest');
const getRemainingRequest = require('./getRemainingRequest');
const getCurrentRequest = require('./getCurrentRequest');
const isUrlRequest = require('./isUrlRequest');
const urlToRequest = require('./urlToRequest');
const parseString = require('./parseString');
const getHashDigest = require('./getHashDigest');
const interpolateName = require('./interpolateName');

exports.getOptions = getOptions;
exports.parseQuery = parseQuery;
exports.stringifyRequest = stringifyRequest;
exports.getRemainingRequest = getRemainingRequest;
exports.getCurrentRequest = getCurrentRequest;
exports.isUrlRequest = isUrlRequest;
exports.urlToRequest = urlToRequest;
exports.parseString = parseString;
exports.getHashDigest = getHashDigest;
exports.interpolateName = interpolateName;


code:
'use strict';

const path = require('path');
const emojisList = require('emojis-list');
const getHashDigest = require('./getHashDigest');

const emojiRegex = /[\uD800-\uDFFF]./;
const emojiList = emojisList.filter((emoji) => emojiRegex.test(emoji));
const emojiCache = {};

function encodeStringToEmoji(content, length) {
  if (emojiCache[content]) {
    return emojiCache[content];
  }

  length = length || 1;

  const emojis = [];

  do {
    if (!emojiList.length) {
      throw new Error('Ran out of emoji');
    }

    const index = Math.floor(Math.random() * emojiList.length);

    emojis.push(emojiList[index]);
    emojiList.splice(index, 1);
  } while (--length > 0);

  const emojiEncoding = emojis.join('');

  emojiCache[content] = emojiEncoding;

  return emojiEncoding;
}

function interpolateName(loaderContext, name, options) {
  let filename;

  const hasQuery =
    loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;

  if (typeof name === 'function') {
    filename = name(
      loaderContext.resourcePath,
      hasQuery ? loaderContext.resourceQuery : undefined
    );
  } else {
    filename = name || '[hash].[ext]';
  }

  const context = options.context;
  const content = options.content;
  const regExp = options.regExp;

  let ext = 'bin';
  let basename = 'file';
  let directory = '';
  let folder = '';
  let query = '';

  if (loaderContext.resourcePath) {
    const parsed = path.parse(loaderContext.resourcePath);
    let resourcePath = loaderContext.resourcePath;

    if (parsed.ext) {
      ext = parsed.ext.substr(1);
    }

    if (parsed.dir) {
      basename = parsed.name;
      resourcePath = parsed.dir + path.sep;
    }

    if (typeof context !== 'undefined') {
      directory = path
        .relative(context, resourcePath + '_')
        .replace(/\\/g, '/')
        .replace(/\.\.(\/)?/g, '_$1');
      directory = directory.substr(0, directory.length - 1);
    } else {
      directory = resourcePath.replace(/\\/g, '/').replace(/\.\.(\/)?/g, '_$1');
    }

    if (directory.length === 1) {
      directory = '';
    } else if (directory.length > 1) {
      folder = path.basename(directory);
    }
  }

  if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
    query = loaderContext.resourceQuery;

    const hashIdx = query.indexOf('#');

    if (hashIdx >= 0) {
      query = query.substr(0, hashIdx);
    }
  }

  let url = filename;

  if (content) {
    // Match hash template
    url = url
      // `hash` and `contenthash` are same in `loader-utils` context
      // let's keep `hash` for backward compatibility
      .replace(
        /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
        (all, hashType, digestType, maxLength) =>
          getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
      )
      .replace(/\[emoji(?::(\d+))?\]/gi, (all, length) =>
        encodeStringToEmoji(content, parseInt(length, 10))
      );
  }

  url = url
    .replace(/\[ext\]/gi, () => ext)
    .replace(/\[name\]/gi, () => basename)
    .replace(/\[path\]/gi, () => directory)
    .replace(/\[folder\]/gi, () => folder)
    .replace(/\[query\]/gi, () => query);

  if (regExp && loaderContext.resourcePath) {
    const match = loaderContext.resourcePath.match(new RegExp(regExp));

    match &&
      match.forEach((matched, i) => {
        url = url.replace(new RegExp('\\[' + i + '\\]', 'ig'), matched);
      });
  }

  if (
    typeof loaderContext.options === 'object' &&
    typeof loaderContext.options.customInterpolateName === 'function'
  ) {
    url = loaderContext.options.customInterpolateName.call(
      loaderContext,
      url,
      name,
      options
    );
  }

  return url;
}

module.exports = interpolateName;


code:
'use strict';

const path = require('path');

function isUrlRequest(url, root) {
  // An URL is not an request if

  // 1. It's an absolute url and it is not `windows` path like `C:\dir\file`
  if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !path.win32.isAbsolute(url)) {
    return false;
  }

  // 2. It's a protocol-relative
  if (/^\/\//.test(url)) {
    return false;
  }

  // 3. It's some kind of url for a template
  if (/^[{}[\]#*;,'§$%&(=?`´^°<>]/.test(url)) {
    return false;
  }

  // 4. It's also not an request if root isn't set and it's a root-relative url
  if ((root === undefined || root === false) && /^\//.test(url)) {
    return false;
  }

  return true;
}

module.exports = isUrlRequest;


code:
'use strict';

const JSON5 = require('json5');

const specialValues = {
  null: null,
  true: true,
  false: false,
};

function parseQuery(query) {
  if (query.substr(0, 1) !== '?') {
    throw new Error(
      "A valid query string passed to parseQuery should begin with '?'"
    );
  }

  query = query.substr(1);

  if (!query) {
    return {};
  }

  if (query.substr(0, 1) === '{' && query.substr(-1) === '}') {
    return JSON5.parse(query);
  }

  const queryArgs = query.split(/[,&]/g);
  const result = Object.create(null);

  queryArgs.forEach((arg) => {
    const idx = arg.indexOf('=');

    if (idx >= 0) {
      let name = arg.substr(0, idx);
      let value = decodeURIComponent(arg.substr(idx + 1));

      // eslint-disable-next-line no-prototype-builtins
      if (specialValues.hasOwnProperty(value)) {
        value = specialValues[value];
      }

      if (name.substr(-2) === '[]') {
        name = decodeURIComponent(name.substr(0, name.length - 2));

        if (!Array.isArray(result[name])) {
          result[name] = [];
        }

        result[name].push(value);
      } else {
        name = decodeURIComponent(name);
        result[name] = value;
      }
    } else {
      if (arg.substr(0, 1) === '-') {
        result[decodeURIComponent(arg.substr(1))] = false;
      } else if (arg.substr(0, 1) === '+') {
        result[decodeURIComponent(arg.substr(1))] = true;
      } else {
        result[decodeURIComponent(arg)] = true;
      }
    }
  });

  return result;
}

module.exports = parseQuery;


code:
'use strict';

function parseString(str) {
  try {
    if (str[0] === '"') {
      return JSON.parse(str);
    }

    if (str[0] === "'" && str.substr(str.length - 1) === "'") {
      return parseString(
        str
          .replace(/\\.|"/g, (x) => (x === '"' ? '\\"' : x))
          .replace(/^'|'$/g, '"')
      );
    }

    return JSON.parse('"' + str + '"');
  } catch (e) {
    return str;
  }
}

module.exports = parseString;


code:
'use strict';

const path = require('path');

const matchRelativePath = /^\.\.?[/\\]/;

function isAbsolutePath(str) {
  return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
}

function isRelativePath(str) {
  return matchRelativePath.test(str);
}

function stringifyRequest(loaderContext, request) {
  const splitted = request.split('!');
  const context =
    loaderContext.context ||
    (loaderContext.options && loaderContext.options.context);

  return JSON.stringify(
    splitted
      .map((part) => {
        // First, separate singlePath from query, because the query might contain paths again
        const splittedPart = part.match(/^(.*?)(\?.*)/);
        const query = splittedPart ? splittedPart[2] : '';
        let singlePath = splittedPart ? splittedPart[1] : part;

        if (isAbsolutePath(singlePath) && context) {
          singlePath = path.relative(context, singlePath);

          if (isAbsolutePath(singlePath)) {
            // If singlePath still matches an absolute path, singlePath was on a different drive than context.
            // In this case, we leave the path platform-specific without replacing any separators.
            // @see https://github.com/webpack/loader-utils/pull/14
            return singlePath + query;
          }

          if (isRelativePath(singlePath) === false) {
            // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
            singlePath = './' + singlePath;
          }
        }

        return singlePath.replace(/\\/g, '/') + query;
      })
      .join('!')
  );
}

module.exports = stringifyRequest;


code:
'use strict';

// we can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;

function urlToRequest(url, root) {
  // Do not rewrite an empty url
  if (url === '') {
    return '';
  }

  const moduleRequestRegex = /^[^?]*~/;
  let request;

  if (matchNativeWin32Path.test(url)) {
    // absolute windows path, keep it
    request = url;
  } else if (root !== undefined && root !== false && /^\//.test(url)) {
    // if root is set and the url is root-relative
    switch (typeof root) {
      // 1. root is a string: root is prefixed to the url
      case 'string':
        // special case: `~` roots convert to module request
        if (moduleRequestRegex.test(root)) {
          request = root.replace(/([^~/])$/, '$1/') + url.slice(1);
        } else {
          request = root + url;
        }
        break;
      // 2. root is `true`: absolute paths are allowed
      //    *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
      case 'boolean':
        request = url;
        break;
      default:
        throw new Error(
          "Unexpected parameters to loader-utils 'urlToRequest': url = " +
            url +
            ', root = ' +
            root +
            '.'
        );
    }
  } else if (/^\.\.?\//.test(url)) {
    // A relative url stays
    request = url;
  } else {
    // every other url is threaded like a relative url
    request = './' + url;
  }

  // A `~` makes the url an module
  if (moduleRequestRegex.test(request)) {
    request = request.replace(moduleRequestRegex, '');
  }

  return request;
}

module.exports = urlToRequest;


loader-utils

author: Tobias Koppers @sokra

description: utils for webpack loaders

lint: eslint lib test

pretest: yarn lint

test: jest

test:ci: jest --coverage

release: yarn test && standard-version

type: git


babel-loader

description: babel module loader for webpack

clean: rimraf lib/

build: babel src/ --out-dir lib/ --copy-files

format: prettier --write --trailing-comma all 'src/**/*.js' 'test/**/*.test.js' 'test/helpers/*.js' && prettier --write --trailing-comma es5 'scripts/*.js'

lint: eslint src test

precommit: lint-staged

prepublish: yarn run clean && yarn run build

preversion: yarn run test

test: yarn run lint && cross-env BABEL_ENV=test yarn run build && yarn run test-only

test-only: nyc ava

keywords: webpack loader babel es6 transpiler module

author: Luis Couto <hello@luiscouto.pt>

reporter: text json

scripts/*.js:
prettier --trailing-comma es5 --write
git add

src/**/*.js:
prettier --trailing-comma all --write
git add

package.json:
node ./scripts/yarn-install.js
git add yarn.lock


code:
{
  "presets": [
    "airbnb"
  ],
  "plugins": [
    "add-module-exports",
    ["transform-replace-object-assign", { "moduleSpecifier": "object.assign" }],
  ],
}


code:
language: node_js
node_js:
  - "13"
  - "12"
  - "11"
  - "10"
  - "9"
  - "8"
  - "7"
  - "6"
  - "5"
  - "4"
  - "iojs-v3"
  - "iojs-v2"
  - "iojs-v1"
  - "0.12"
import:
  - ljharb/travis-ci:node/latest-npm.yml
  - ljharb/travis-ci:node/greenkeeper.yml
  - ljharb/travis-ci:node/dependabot.yml
script: 'npm run tests-only'
sudo: false
env:
  - TEST=true
matrix:
  fast_finish: true
  include:
    - node_js: "lts/*"
      env: PRETEST=true
      script: 'npm run pretest'
  allow_failures:
    - node_js: "9"
    - node_js: "7"
    - node_js: "5"
    - node_js: "iojs-v3"
    - node_js: "iojs-v2"
    - node_js: "iojs-v1"
    - env: TEST=true ALLOW_FAILURE=true


code:
## Unreleased

## v2.3.3
- [Fix] Generate webpack-compatible output with static string arg (#84)
- [Fix] Handle visiting the same path gracefully (#71)

## v2.3.2
- [Fix] avoid using reserved param name in babel 7 templates
- [Dev Deps] update `airbnb-js-shims`

## v2.3.1
- [Fix] Evaluate `import()` argument synchronously (#85)
- [Dev Deps] update `eslint`, `eslint-config-airbnb-base`, `in-publish`, `rimraf`, `safe-publish-latest`, `tape`

## v2.3.0
- [New] expose createDynamicImportTransform and getImportSource (#75)
- [Docs] Document noInterop option (#70)

## v2.2.0
- [Refactor] remove dependency on babel-plugin-syntax-dynamic-import
- [Dev Deps] update `airbnb-js-shims`, `babel-preset-airbnb`, `eslint`

## v2.1.0
- [New] add `noInterop` option (#57)
- [Docs] Fix typo "correct" -> "correctly" in readme (#55)
- [Dev Deps] update `airbnb-js-shims`, `babel-eslint`, `babel-preset-airbnb`, `eslint`, `eslint-config-airbnb-base`, `eslint-plugin-import`, `safe-publish-latest`

## v2.0.0
- [Breaking] always return a module namespace object (#52, #47)
- [Breaking] remove `.default` on entry points (#27)
- [Docs] removed $ before npm command (#35)
- [Docs] Improve README.md with a code example (#41)
- [Dev Deps] update `airbnb-js-shims`, `babel-core`, `babel-eslint`, `eslint`, `eslint-plugin-import`
- [Tests] switch from mocha to tape, so we can support older nodes

## v1.2.0
- [New] support comments (#37)
- [Refactor] Use template and types from the babel object (#32)
- [Tests] on `node` `v9`; pin included builds to LTS
- [Dev Deps] update `eslint`, `eslint-config-airbnb-base`, `mocha`, `rimraf`

## v1.1.0
- Visit Import nodes instead of CallExpressions (#30)
- [Deps] update `babel-template`, `babel-types`
- [Dev Deps] update `airbnb-js-shims`, `babel-cli`, `babel-core`, `babel-preset-airbnb`, `babel-register`, `chai`, `eslint`, `eslint-config-airbnb-base`, `eslint-plugin-import`, `mocha`
- [Tests] on `node` `v8`
- [Tests] use `nvm install-latest-npm` so newer npm doesn’t break older node

## v1.0.2
- [Fix] Ensure it works with the ES2015 preset too (#12, #16)
- [Deps] update `babel-template`, `babel-types`
- [Dev Deps] update `babel-cli`, `babel-core`, `babel-eslint`, `babel-register`, `eslint`, `eslint-config-airbnb-base`, `mocha`

## v1.0.1
- [Fix] Move `in-publish` to devDeps (#11)
- [Fix] ensure dynamic `import()` input is properly stringified (#2)
- [Fix] async timing of dynamic import to match spec (#3)
- [Fix] Remove spaces in template strings and update Babel (#10)
- [Deps] update `babel-template`, `babel-types`
- [Deps] update `babel-types` (#4, #5, #6)
- [Dev Deps] update `babel-cli`, `babel-core`, `babel-eslint`, `babel-register`, `eslint`, `eslint-config-airbnb-base`, `eslint-plugin-import`, `mocha`, `rimraf`

## v1.0.0
- Initial full release.


code:
# babel-plugin-dynamic-import-node

Babel plugin to transpile `import()` to a deferred `require()`, for node. Matches the [proposed spec](https://github.com/domenic/proposal-import-function).

**NOTE:** Babylon >= v6.12.0 is required to correctly parse dynamic imports.

## Installation

```sh
npm install babel-plugin-dynamic-import-node --save-dev
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
  "plugins": ["dynamic-import-node"]
}
```

#### Options

- *`noInterop`* - A boolean value, that if true will not interop the require calls. Useful to avoid using `require('module').default` on commonjs modules.

```json
{
  "plugins": [
    ["dynamic-import-node", { "noInterop": true }]
  ]
}
```

### Via CLI

```sh
$ babel --plugins dynamic-import-node script.js
```

### Via Node API

```javascript
require('babel-core').transform('code', {
  plugins: ['dynamic-import-node']
});
```

### Code Example
```javascript
Promise.all([
  import('./lib/import1'),
  import('./lib/import2')
 ]).then(([
   Import1,
   Import2
  ]) => {
   console.log(Import1);
   /* CODE HERE*/
  });
```


code:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports['default'] = function (api) {
  var transformImport = (0, _utils.createDynamicImportTransform)(api);

  return {
    // NOTE: Once we drop support for Babel <= v6 we should
    // update this to import from @babel/plugin-syntax-dynamic-import.
    // https://www.npmjs.com/package/@babel/plugin-syntax-dynamic-import
    manipulateOptions: function () {
      function manipulateOptions(opts, parserOpts) {
        parserOpts.plugins.push('dynamicImport');
      }

      return manipulateOptions;
    }(),

    visitor: {
      Import: function () {
        function Import(path) {
          transformImport(this, path);
        }

        return Import;
      }()
    }
  };
};

var _utils = require('./utils');

module.exports = exports['default'];


code:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.getImportSource = getImportSource;
exports.createDynamicImportTransform = createDynamicImportTransform;
function getImportSource(t, callNode) {
  var importArguments = callNode.arguments;

  var _importArguments = _slicedToArray(importArguments, 1),
      importPath = _importArguments[0];

  var isString = t.isStringLiteral(importPath) || t.isTemplateLiteral(importPath);
  if (isString) {
    t.removeComments(importPath);
    return importPath;
  }

  return t.templateLiteral([t.templateElement({ raw: '', cooked: '' }), t.templateElement({ raw: '', cooked: '' }, true)], importArguments);
}

function createDynamicImportTransform(_ref) {
  var template = _ref.template,
      t = _ref.types;

  var builders = {
    'static': {
      interop: template('Promise.resolve().then(() => INTEROP(require(SOURCE)))'),
      noInterop: template('Promise.resolve().then(() => require(SOURCE))')
    },
    dynamic: {
      interop: template('Promise.resolve(SOURCE).then(s => INTEROP(require(s)))'),
      noInterop: template('Promise.resolve(SOURCE).then(s => require(s))')
    }
  };

  var visited = typeof WeakSet === 'function' && new WeakSet();

  var isString = function isString(node) {
    return t.isStringLiteral(node) || t.isTemplateLiteral(node) && node.expressions.length === 0;
  };

  return function (context, path) {
    if (visited) {
      if (visited.has(path)) {
        return;
      }
      visited.add(path);
    }

    var SOURCE = getImportSource(t, path.parent);

    var builder = isString(SOURCE) ? builders['static'] : builders.dynamic;

    var newImport = context.opts.noInterop ? builder.noInterop({ SOURCE: SOURCE }) : builder.interop({ SOURCE: SOURCE, INTEROP: context.addHelper('interopRequireWildcard') });

    path.parentPath.replaceWith(newImport);
  };
}


babel-plugin-dynamic-import-node

description: Babel plugin to transpile import() to a deferred require(), for node

test: test

clean: rimraf lib

prebuild: npm run clean

build: babel src --out-dir lib

pretest: npm run lint

test: npm run tests-only

tests-only: tape --require airbnb-js-shims --require babel-register test

lint: eslint .

prepublish: not-in-publish || (safe-publish-latest && npm run build)

check-changelog: expr $(git status --porcelain 2>/dev/null| grep "^\s*M.*CHANGELOG.md" | wc -l) >/dev/null || (echo 'Please edit CHANGELOG.md' && exit 1)

check-only-changelog-changed: (expr $(git status --porcelain 2>/dev/null| grep -v "CHANGELOG.md" | wc -l) >/dev/null && echo 'Only CHANGELOG.md may have uncommitted changes' && exit 1) || exit 0

version:major: npm --no-git-tag-version version major

version:minor: npm --no-git-tag-version version minor

version:patch: npm --no-git-tag-version version patch

postversion: git commit package.json CHANGELOG.md -m "v$npm_package_version" && npm run tag && git push && git push --tags

preversion: npm run test && npm run check-changelog && npm run check-only-changelog-changed

tag: git tag v$npm_package_version

keywords: babel plugin dynamic import node


code:
// Re-export lib/utils, so that consumers can import
// babel-plugin-dynamic-import-node/utils instead of
// babel-plugin-dynamic-import-node/lib/utils

// eslint-disable-next-line import/no-unresolved
module.exports = require('./lib/utils');


code:
# babel-plugin-polyfill-corejs2

## Install

Using npm:

```sh
npm install --save-dev babel-plugin-polyfill-corejs2
```

or using yarn:

```sh
yarn add babel-plugin-polyfill-corejs2 --dev
```

## Usage

Add this plugin to your Babel configuration:

```json
{
  "plugins": [["polyfill-corejs2", { "method": "usage-global" }]]
}
```

This package supports the `usage-pure`, `usage-global`, and `entry-global` methods.
When `entry-global` is used, it replaces imports to `core-js`.