code:
const {
  MAX_SAFE_COMPONENT_LENGTH,
  MAX_SAFE_BUILD_LENGTH,
  MAX_LENGTH,
} = require('./constants')
const debug = require('./debug')
exports = module.exports = {}

// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const t = exports.t = {}
let R = 0

const LETTERDASHNUMBER = '[a-zA-Z0-9-]'

// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
  ['\\s', 1],
  ['\\d', MAX_LENGTH],
  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]

const makeSafeRegex = (value) => {
  for (const [token, max] of safeRegexReplacements) {
    value = value
      .split(`${token}*`).join(`${token}{0,${max}}`)
      .split(`${token}+`).join(`${token}{1,${max}}`)
  }
  return value
}

const createToken = (name, value, isGlobal) => {
  const safe = makeSafeRegex(value)
  const index = R++
  debug(name, index, value)
  t[name] = index
  src[index] = value
  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}

// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.

// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.

createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')

// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.

createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)

// ## Main Version
// Three dot-separated numeric identifiers.

createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
                   `(${src[t.NUMERICIDENTIFIER]})`)

createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)

// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.

createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
}|${src[t.NONNUMERICIDENTIFIER]})`)

createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
}|${src[t.NONNUMERICIDENTIFIER]})`)

// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.

createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)

createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)

// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.

createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)

// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.

createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)

// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.

// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.

createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
  src[t.BUILD]}?`)

createToken('FULL', `^${src[t.FULLPLAIN]}$`)

// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
  src[t.BUILD]}?`)

createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)

createToken('GTLT', '((?:<|>)?=?)')

// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)

createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:${src[t.PRERELEASE]})?${
                     src[t.BUILD]}?` +
                   `)?)?`)

createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:${src[t.PRERELEASELOOSE]})?${
                          src[t.BUILD]}?` +
                        `)?)?`)

createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)

// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
              `(?:${src[t.PRERELEASE]})?` +
              `(?:${src[t.BUILD]})?` +
              `(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)

// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')

createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'

createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)

// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')

createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'

createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)

// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)

// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'

// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
                   `\\s+-\\s+` +
                   `(${src[t.XRANGEPLAIN]})` +
                   `\\s*$`)

createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
                        `\\s+-\\s+` +
                        `(${src[t.XRANGEPLAINLOOSE]})` +
                        `\\s*$`)

// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')


semver

description: The semantic version parser used by npm.

test: tap

snap: tap

lint: eslint "**/*.{js,cjs,ts,mjs,jsx,tsx}"

postlint: template-oss-check

lintfix: npm run lint -- --fix

posttest: npm run lint

template-oss-apply: template-oss-apply --force

license: ISC

type: git

files: bin/ lib/ classes/ functions/ internal/ ranges/ index.js preload.js range.bnf

nyc-arg: --exclude tap-snapshots/**

author: GitHub Inc.

//@npmcli/template-oss: This file is partially managed by @npmcli/template-oss. Edits may be overwritten.

publish: true

license: mit


code:
// XXX remove in v8 or beyond
module.exports = require('./index.js')


code:
range-set  ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range      ::= hyphen | simple ( ' ' simple ) * | ''
hyphen     ::= partial ' - ' partial
simple     ::= primitive | partial | tilde | caret
primitive  ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial    ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr         ::= 'x' | 'X' | '*' | nr
nr         ::= '0' | [1-9] ( [0-9] ) *
tilde      ::= '~' partial
caret      ::= '^' partial
qualifier  ::= ( '-' pre )? ( '+' build )?
pre        ::= parts
build      ::= parts
parts      ::= part ( '.' part ) *
part       ::= nr | [-0-9A-Za-z]+


code:
// Determine if version is greater than all the versions possible in the range.
const outside = require('./outside')
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr


code:
const Range = require('../classes/range')
const intersects = (r1, r2, options) => {
  r1 = new Range(r1, options)
  r2 = new Range(r2, options)
  return r1.intersects(r2, options)
}
module.exports = intersects


code:
const outside = require('./outside')
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr


code:
const SemVer = require('../classes/semver')
const Range = require('../classes/range')

const maxSatisfying = (versions, range, options) => {
  let max = null
  let maxSV = null
  let rangeObj = null
  try {
    rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach((v) => {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!max || maxSV.compare(v) === -1) {
        // compare(max, v, true)
        max = v
        maxSV = new SemVer(max, options)
      }
    }
  })
  return max
}
module.exports = maxSatisfying


code:
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const minSatisfying = (versions, range, options) => {
  let min = null
  let minSV = null
  let rangeObj = null
  try {
    rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach((v) => {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!min || minSV.compare(v) === 1) {
        // compare(min, v, true)
        min = v
        minSV = new SemVer(min, options)
      }
    }
  })
  return min
}
module.exports = minSatisfying


code:
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const gt = require('../functions/gt')

const minVersion = (range, loose) => {
  range = new Range(range, loose)

  let minver = new SemVer('0.0.0')
  if (range.test(minver)) {
    return minver
  }

  minver = new SemVer('0.0.0-0')
  if (range.test(minver)) {
    return minver
  }

  minver = null
  for (let i = 0; i < range.set.length; ++i) {
    const comparators = range.set[i]

    let setMin = null
    comparators.forEach((comparator) => {
      // Clone to avoid manipulating the comparator's semver object.
      const compver = new SemVer(comparator.semver.version)
      switch (comparator.operator) {
        case '>':
          if (compver.prerelease.length === 0) {
            compver.patch++
          } else {
            compver.prerelease.push(0)
          }
          compver.raw = compver.format()
          /* fallthrough */
        case '':
        case '>=':
          if (!setMin || gt(compver, setMin)) {
            setMin = compver
          }
          break
        case '<':
        case '<=':
          /* Ignore maximum versions */
          break
        /* istanbul ignore next */
        default:
          throw new Error(`Unexpected operation: ${comparator.operator}`)
      }
    })
    if (setMin && (!minver || gt(minver, setMin))) {
      minver = setMin
    }
  }

  if (minver && range.test(minver)) {
    return minver
  }

  return null
}
module.exports = minVersion


code:
const SemVer = require('../classes/semver')
const Comparator = require('../classes/comparator')
const { ANY } = Comparator
const Range = require('../classes/range')
const satisfies = require('../functions/satisfies')
const gt = require('../functions/gt')
const lt = require('../functions/lt')
const lte = require('../functions/lte')
const gte = require('../functions/gte')

const outside = (version, range, hilo, options) => {
  version = new SemVer(version, options)
  range = new Range(range, options)

  let gtfn, ltefn, ltfn, comp, ecomp
  switch (hilo) {
    case '>':
      gtfn = gt
      ltefn = lte
      ltfn = lt
      comp = '>'
      ecomp = '>='
      break
    case '<':
      gtfn = lt
      ltefn = gte
      ltfn = gt
      comp = '<'
      ecomp = '<='
      break
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"')
  }

  // If it satisfies the range it is not outside
  if (satisfies(version, range, options)) {
    return false
  }

  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.

  for (let i = 0; i < range.set.length; ++i) {
    const comparators = range.set[i]

    let high = null
    let low = null

    comparators.forEach((comparator) => {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator
      low = low || comparator
      if (gtfn(comparator.semver, high.semver, options)) {
        high = comparator
      } else if (ltfn(comparator.semver, low.semver, options)) {
        low = comparator
      }
    })

    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false
    }

    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false
    }
  }
  return true
}

module.exports = outside


code:
// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
module.exports = (versions, range, options) => {
  const set = []
  let first = null
  let prev = null
  const v = versions.sort((a, b) => compare(a, b, options))
  for (const version of v) {
    const included = satisfies(version, range, options)
    if (included) {
      prev = version
      if (!first) {
        first = version
      }
    } else {
      if (prev) {
        set.push([first, prev])
      }
      prev = null
      first = null
    }
  }
  if (first) {
    set.push([first, null])
  }

  const ranges = []
  for (const [min, max] of set) {
    if (min === max) {
      ranges.push(min)
    } else if (!max && min === v[0]) {
      ranges.push('*')
    } else if (!max) {
      ranges.push(`>=${min}`)
    } else if (min === v[0]) {
      ranges.push(`<=${max}`)
    } else {
      ranges.push(`${min} - ${max}`)
    }
  }
  const simplified = ranges.join(' || ')
  const original = typeof range.raw === 'string' ? range.raw : String(range)
  return simplified.length < original.length ? simplified : range
}


code:
const Range = require('../classes/range.js')
const Comparator = require('../classes/comparator.js')
const { ANY } = Comparator
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')

// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
//   some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
//   - If C is only the ANY comparator, return true
//   - Else if in prerelease mode, return false
//   - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
//   - if in prerelease mode, return true
//   - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
//   - If GT, and EQ does not satisfy GT, return true (null set)
//   - If LT, and EQ does not satisfy LT, return true (null set)
//   - If EQ satisfies every C, return true
//   - Else return false
// - If GT
//   - If GT.semver is lower than any > or >= comp in C, return false
//   - If GT is >=, and GT.semver does not satisfy every C, return false
//   - If GT.semver has a prerelease, and not in prerelease mode
//     - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
//   - If LT.semver is greater than any < or <= comp in C, return false
//   - If LT is <=, and LT.semver does not satisfy every C, return false
//   - If GT.semver has a prerelease, and not in prerelease mode
//     - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true

const subset = (sub, dom, options = {}) => {
  if (sub === dom) {
    return true
  }

  sub = new Range(sub, options)
  dom = new Range(dom, options)
  let sawNonNull = false

  OUTER: for (const simpleSub of sub.set) {
    for (const simpleDom of dom.set) {
      const isSub = simpleSubset(simpleSub, simpleDom, options)
      sawNonNull = sawNonNull || isSub !== null
      if (isSub) {
        continue OUTER
      }
    }
    // the null set is a subset of everything, but null simple ranges in
    // a complex range should be ignored.  so if we saw a non-null range,
    // then we know this isn't a subset, but if EVERY simple range was null,
    // then it is a subset.
    if (sawNonNull) {
      return false
    }
  }
  return true
}

const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
const minimumVersion = [new Comparator('>=0.0.0')]

const simpleSubset = (sub, dom, options) => {
  if (sub === dom) {
    return true
  }

  if (sub.length === 1 && sub[0].semver === ANY) {
    if (dom.length === 1 && dom[0].semver === ANY) {
      return true
    } else if (options.includePrerelease) {
      sub = minimumVersionWithPreRelease
    } else {
      sub = minimumVersion
    }
  }

  if (dom.length === 1 && dom[0].semver === ANY) {
    if (options.includePrerelease) {
      return true
    } else {
      dom = minimumVersion
    }
  }

  const eqSet = new Set()
  let gt, lt
  for (const c of sub) {
    if (c.operator === '>' || c.operator === '>=') {
      gt = higherGT(gt, c, options)
    } else if (c.operator === '<' || c.operator === '<=') {
      lt = lowerLT(lt, c, options)
    } else {
      eqSet.add(c.semver)
    }
  }

  if (eqSet.size > 1) {
    return null
  }

  let gtltComp
  if (gt && lt) {
    gtltComp = compare(gt.semver, lt.semver, options)
    if (gtltComp > 0) {
      return null
    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
      return null
    }
  }

  // will iterate one or zero times
  for (const eq of eqSet) {
    if (gt && !satisfies(eq, String(gt), options)) {
      return null
    }

    if (lt && !satisfies(eq, String(lt), options)) {
      return null
    }

    for (const c of dom) {
      if (!satisfies(eq, String(c), options)) {
        return false
      }
    }

    return true
  }

  let higher, lower
  let hasDomLT, hasDomGT
  // if the subset has a prerelease, we need a comparator in the superset
  // with the same tuple and a prerelease, or it's not a subset
  let needDomLTPre = lt &&
    !options.includePrerelease &&
    lt.semver.prerelease.length ? lt.semver : false
  let needDomGTPre = gt &&
    !options.includePrerelease &&
    gt.semver.prerelease.length ? gt.semver : false
  // exception: <1.2.3-0 is the same as <1.2.3
  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
    needDomLTPre = false
  }

  for (const c of dom) {
    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
    if (gt) {
      if (needDomGTPre) {
        if (c.semver.prerelease && c.semver.prerelease.length &&
            c.semver.major === needDomGTPre.major &&
            c.semver.minor === needDomGTPre.minor &&
            c.semver.patch === needDomGTPre.patch) {
          needDomGTPre = false
        }
      }
      if (c.operator === '>' || c.operator === '>=') {
        higher = higherGT(gt, c, options)
        if (higher === c && higher !== gt) {
          return false
        }
      } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
        return false
      }
    }
    if (lt) {
      if (needDomLTPre) {
        if (c.semver.prerelease && c.semver.prerelease.length &&
            c.semver.major === needDomLTPre.major &&
            c.semver.minor === needDomLTPre.minor &&
            c.semver.patch === needDomLTPre.patch) {
          needDomLTPre = false
        }
      }
      if (c.operator === '<' || c.operator === '<=') {
        lower = lowerLT(lt, c, options)
        if (lower === c && lower !== lt) {
          return false
        }
      } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
        return false
      }
    }
    if (!c.operator && (lt || gt) && gtltComp !== 0) {
      return false
    }
  }

  // if there was a < or >, and nothing in the dom, then must be false
  // UNLESS it was limited by another range in the other direction.
  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
  if (gt && hasDomLT && !lt && gtltComp !== 0) {
    return false
  }

  if (lt && hasDomGT && !gt && gtltComp !== 0) {
    return false
  }

  // we needed a prerelease range in a specific tuple, but didn't get one
  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,
  // because it includes prereleases in the 1.2.3 tuple
  if (needDomGTPre || needDomLTPre) {
    return false
  }

  return true
}

// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
  if (!a) {
    return b
  }
  const comp = compare(a.semver, b.semver, options)
  return comp > 0 ? a
    : comp < 0 ? b
    : b.operator === '>' && a.operator === '>=' ? b
    : a
}

// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
  if (!a) {
    return b
  }
  const comp = compare(a.semver, b.semver, options)
  return comp < 0 ? a
    : comp > 0 ? b
    : b.operator === '<' && a.operator === '<=' ? b
    : a
}

module.exports = subset


code:
const Range = require('../classes/range')

// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
  new Range(range, options).set
    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))

module.exports = toComparators


code:
const Range = require('../classes/range')
const validRange = (range, options) => {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, options).range || '*'
  } catch (er) {
    return null
  }
}
module.exports = validRange


vue-eslint-parser

description: The ESLint custom parser for `.vue` files.

prebuild: npm run -s clean

build: tsc --module es2015 && rollup -c -o index.js && dts-bundle --name vue-eslint-parser --main .temp/index.d.ts --out ../index.d.ts

clean: rimraf .nyc_output .temp coverage index.*

codecov: codecov

lint: eslint src test package.json --ext .js,.ts

setup: git submodule update --init && cd test/fixtures/eslint && npm install

pretest: run-s build lint

test: npm run -s test:mocha

test:mocha: mocha --require ts-node/register "test/*.js" --reporter dot --timeout 60000

test:cover: nyc mocha "test/*.js" --reporter dot --timeout 60000

test:debug: mocha --require ts-node/register/transpile-only "test/*.js" --reporter dot --timeout 60000

update-fixtures: ts-node --transpile-only scripts/update-fixtures-ast.js && ts-node --transpile-only scripts/update-fixtures-document-fragment.js

preversion: npm test

version: npm run -s build

postversion: git push && git push --tags

prewatch: npm run -s clean

watch: run-p watch:*

watch:tsc: tsc --module es2015 --watch

watch:rollup: wait-on .temp/index.js && rollup -c -o index.js --watch

watch:test: wait-on index.js && warun index.js "test/*.js" "test/fixtures/ast/*/*.json" "test/fixtures/*" --debounce 1000 --no-initial -- nyc mocha "test/*.js" --reporter dot --timeout 10000

watch:update-ast: wait-on index.js && warun index.js "test/fixtures/ast/*/*.vue" -- node scripts/update-fixtures-ast.js

watch:coverage-report: wait-on coverage/lcov-report/index.html && opener coverage/lcov-report/index.html

author: Toru Nagashima

license: MIT


code:
# vue-hot-reload-api

> Note: `vue-hot-reload-api@2.x` only works with `vue@2.x`

Hot reload API for Vue components. This is what [vue-loader](https://github.com/vuejs/vue-loader) and [vueify](https://github.com/vuejs/vueify) use under the hood.

## Usage

You will only be using this if you are writing some build toolchain based on Vue components. For normal application usage, just use `vue-loader` or `vueify`.

``` js
// define a component as an options object
const myComponentOptions = {
  data () { ... },
  created () { ... },
  render () { ... }
}

// assuming Webpack's HMR API.
// https://webpack.js.org/guides/hot-module-replacement/
if (module.hot) {
  const api = require('vue-hot-reload-api')
  const Vue = require('vue')

  // make the API aware of the Vue that you are using.
  // also checks compatibility.
  api.install(Vue)

  // compatibility can be checked via api.compatible after installation
  if (!api.compatible) {
    throw new Error('vue-hot-reload-api is not compatible with the version of Vue you are using.')
  }

  // indicate this module can be hot-reloaded
  module.hot.accept()

  if (!module.hot.data) {
    // for each component option object to be hot-reloaded,
    // you need to create a record for it with a unique id.
    // do this once on startup.
    api.createRecord('very-unique-id', myComponentOptions)
  } else {
    // if a component has only its template or render function changed,
    // you can force a re-render for all its active instances without
    // destroying/re-creating them. This keeps all current app state intact.
    api.rerender('very-unique-id', myComponentOptions)

    // --- OR ---

    // if a component has non-template/render options changed,
    // it needs to be fully reloaded. This will destroy and re-create all its
    // active instances (and their children).
    api.reload('very-unique-id', myComponentOptions)
  }
}
```

## License

[MIT](http://opensource.org/licenses/MIT)


code:
var Vue // late bind
var version
var map = Object.create(null)
if (typeof window !== 'undefined') {
  window.__VUE_HOT_MAP__ = map
}
var installed = false
var isBrowserify = false
var initHookName = 'beforeCreate'

exports.install = function (vue, browserify) {
  if (installed) { return }
  installed = true

  Vue = vue.__esModule ? vue.default : vue
  version = Vue.version.split('.').map(Number)
  isBrowserify = browserify

  // compat with < 2.0.0-alpha.7
  if (Vue.config._lifecycleHooks.indexOf('init') > -1) {
    initHookName = 'init'
  }

  exports.compatible = version[0] >= 2
  if (!exports.compatible) {
    console.warn(
      '[HMR] You are using a version of vue-hot-reload-api that is ' +
        'only compatible with Vue.js core ^2.0.0.'
    )
    return
  }
}

/**
 * Create a record for a hot module, which keeps track of its constructor
 * and instances
 *
 * @param {String} id
 * @param {Object} options
 */

exports.createRecord = function (id, options) {
  if(map[id]) { return }

  var Ctor = null
  if (typeof options === 'function') {
    Ctor = options
    options = Ctor.options
  }
  makeOptionsHot(id, options)
  map[id] = {
    Ctor: Ctor,
    options: options,
    instances: []
  }
}

/**
 * Check if module is recorded
 *
 * @param {String} id
 */

exports.isRecorded = function (id) {
  return typeof map[id] !== 'undefined'
}

/**
 * Make a Component options object hot.
 *
 * @param {String} id
 * @param {Object} options
 */

function makeOptionsHot(id, options) {
  if (options.functional) {
    var render = options.render
    options.render = function (h, ctx) {
      var instances = map[id].instances
      if (ctx && instances.indexOf(ctx.parent) < 0) {
        instances.push(ctx.parent)
      }
      return render(h, ctx)
    }
  } else {
    injectHook(options, initHookName, function() {
      var record = map[id]
      if (!record.Ctor) {
        record.Ctor = this.constructor
      }
      record.instances.push(this)
    })
    injectHook(options, 'beforeDestroy', function() {
      var instances = map[id].instances
      instances.splice(instances.indexOf(this), 1)
    })
  }
}

/**
 * Inject a hook to a hot reloadable component so that
 * we can keep track of it.
 *
 * @param {Object} options
 * @param {String} name
 * @param {Function} hook
 */

function injectHook(options, name, hook) {
  var existing = options[name]
  options[name] = existing
    ? Array.isArray(existing) ? existing.concat(hook) : [existing, hook]
    : [hook]
}

function tryWrap(fn) {
  return function (id, arg) {
    try {
      fn(id, arg)
    } catch (e) {
      console.error(e)
      console.warn(
        'Something went wrong during Vue component hot-reload. Full reload required.'
      )
    }
  }
}

function updateOptions (oldOptions, newOptions) {
  for (var key in oldOptions) {
    if (!(key in newOptions)) {
      delete oldOptions[key]
    }
  }
  for (var key$1 in newOptions) {
    oldOptions[key$1] = newOptions[key$1]
  }
}

exports.rerender = tryWrap(function (id, options) {
  var record = map[id]
  if (!options) {
    record.instances.slice().forEach(function (instance) {
      instance.$forceUpdate()
    })
    return
  }
  if (typeof options === 'function') {
    options = options.options
  }
  if (record.Ctor) {
    record.Ctor.options.render = options.render
    record.Ctor.options.staticRenderFns = options.staticRenderFns
    record.instances.slice().forEach(function (instance) {
      instance.$options.render = options.render
      instance.$options.staticRenderFns = options.staticRenderFns
      // reset static trees
      // pre 2.5, all static trees are cached together on the instance
      if (instance._staticTrees) {
        instance._staticTrees = []
      }
      // 2.5.0
      if (Array.isArray(record.Ctor.options.cached)) {
        record.Ctor.options.cached = []
      }
      // 2.5.3
      if (Array.isArray(instance.$options.cached)) {
        instance.$options.cached = []
      }

      // post 2.5.4: v-once trees are cached on instance._staticTrees.
      // Pure static trees are cached on the staticRenderFns array
      // (both already reset above)

      // 2.6: temporarily mark rendered scoped slots as unstable so that
      // child components can be forced to update
      var restore = patchScopedSlots(instance)
      instance.$forceUpdate()
      instance.$nextTick(restore)
    })
  } else {
    // functional or no instance created yet
    record.options.render = options.render
    record.options.staticRenderFns = options.staticRenderFns

    // handle functional component re-render
    if (record.options.functional) {
      // rerender with full options
      if (Object.keys(options).length > 2) {
        updateOptions(record.options, options)
      } else {
        // template-only rerender.
        // need to inject the style injection code for CSS modules
        // to work properly.
        var injectStyles = record.options._injectStyles
        if (injectStyles) {
          var render = options.render
          record.options.render = function (h, ctx) {
            injectStyles.call(ctx)
            return render(h, ctx)
          }
        }
      }
      record.options._Ctor = null
      // 2.5.3
      if (Array.isArray(record.options.cached)) {
        record.options.cached = []
      }
      record.instances.slice().forEach(function (instance) {
        instance.$forceUpdate()
      })
    }
  }
})

exports.reload = tryWrap(function (id, options) {
  var record = map[id]
  if (options) {
    if (typeof options === 'function') {
      options = options.options
    }
    makeOptionsHot(id, options)
    if (record.Ctor) {
      if (version[1] < 2) {
        // preserve pre 2.2 behavior for global mixin handling
        record.Ctor.extendOptions = options
      }
      var newCtor = record.Ctor.super.extend(options)
      // prevent record.options._Ctor from being overwritten accidentally
      newCtor.options._Ctor = record.options._Ctor
      record.Ctor.options = newCtor.options
      record.Ctor.cid = newCtor.cid
      record.Ctor.prototype = newCtor.prototype
      if (newCtor.release) {
        // temporary global mixin strategy used in < 2.0.0-alpha.6
        newCtor.release()
      }
    } else {
      updateOptions(record.options, options)
    }
  }
  record.instances.slice().forEach(function (instance) {
    if (instance.$vnode && instance.$vnode.context) {
      instance.$vnode.context.$forceUpdate()
    } else {
      console.warn(
        'Root or manually mounted instance modified. Full reload required.'
      )
    }
  })
})

// 2.6 optimizes template-compiled scoped slots and skips updates if child
// only uses scoped slots. We need to patch the scoped slots resolving helper
// to temporarily mark all scoped slots as unstable in order to force child
// updates.
function patchScopedSlots (instance) {
  if (!instance._u) { return }
  // https://github.com/vuejs/vue/blob/dev/src/core/instance/render-helpers/resolve-scoped-slots.js
  var original = instance._u
  instance._u = function (slots) {
    try {
      // 2.6.4 ~ 2.6.6
      return original(slots, true)
    } catch (e) {
      // 2.5 / >= 2.6.7
      return original(slots, null, true)
    }
  }
  return function () {
    instance._u = original
  }
}


vue-hot-reload-api

description: hot reload api for *.vue components

build: buble src -o dist

test: jest

prepublishOnly: npm run test && npm run build

keywords: vue hot reload

author: Evan You


code:
# vue-loader [![ci](https://github.com/vuejs/vue-loader/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/vuejs/vue-loader/actions/workflows/ci.yml)

> webpack loader for Vue Single-File Components

- [Documentation](https://vue-loader.vuejs.org)

## v17.2.1+ Only Options

- `experimentalInlineMatchResource: boolean`: enable [Inline matchResource](https://webpack.js.org/api/loaders/#inline-matchresource) for rule matching for vue-loader.

## v16+ Only Options

- `reactivityTransform: boolean`: enable [Vue Reactivity Transform](https://github.com/vuejs/rfcs/discussions/369) (SFCs only).

- ~~`refSugar: boolean`: **removed.** use `reactivityTransform` instead.~~

- `customElement: boolean | RegExp`: enable custom elements mode. An SFC loaded in custom elements mode inlines its `<style>` tags as strings under the component's `styles` option. When used with `defineCustomElement` from Vue core, the styles will be injected into the custom element's shadow root.

  - Default is `/\.ce\.vue$/`
  - Setting to `true` will process all `.vue` files in custom element mode.

- `enableTsInTemplate: boolean` (16.8+): allow TS expressions in templates when `<script>` has `lang="ts"`. Defaults to `true`.

  - When used with `ts-loader`, due to `ts-loader`'s cache invalidation behavior, it sometimes prevents the template from being hot-reloaded in isolation, causing the component to reload despite only the template being edited. If this is annoying, you can set this option to `false` (and avoid using TS expressions in templates).

  - Alternatively, leave this option on (by default) and use [`esbuild-loader`](https://github.com/privatenumber/esbuild-loader) to transpile TS instead, which doesn't suffer from this problem (it's also a lot faster). However, do note you will need to rely on TS type checking from other sources (e.g. IDE or `vue-tsc`).

## What is Vue Loader?

`vue-loader` is a loader for [webpack](https://webpack.js.org/) that allows you to author Vue components in a format called [Single-File Components (SFCs)](./docs/spec.md):

```vue
<template>
  <div class="example">{{ msg }}</div>
</template>

<script>
export default {
  data() {
    return {
      msg: 'Hello world!',
    }
  },
}
</script>

<style>
.example {
  color: red;
}
</style>
```

There are many cool features provided by `vue-loader`:

- Allows using other webpack loaders for each part of a Vue component, for example Sass for `<style>` and Pug for `<template>`;
- Allows custom blocks in a `.vue` file that can have custom loader chains applied to them;
- Treat static assets referenced in `<style>` and `<template>` as module dependencies and handle them with webpack loaders;
- Simulate scoped CSS for each component;
- State-preserving hot-reloading during development.

In a nutshell, the combination of webpack and `vue-loader` gives you a modern, flexible and extremely powerful front-end workflow for authoring Vue.js applications.

## How It Works

> The following section is for maintainers and contributors who are interested in the internal implementation details of `vue-loader`, and is **not** required knowledge for end users.

`vue-loader` is not a simple source transform loader. It handles each language blocks inside an SFC with its own dedicated loader chain (you can think of each block as a "virtual module"), and finally assembles the blocks together into the final module. Here's a brief overview of how the whole thing works:

1. `vue-loader` parses the SFC source code into an _SFC Descriptor_ using `@vue/compiler-sfc`. It then generates an import for each language block so the actual returned module code looks like this:

   ```js
   // code returned from the main loader for 'source.vue'

   // import the <template> block
   import render from 'source.vue?vue&type=template'
   // import the <script> block
   import script from 'source.vue?vue&type=script'
   export * from 'source.vue?vue&type=script'
   // import <style> blocks
   import 'source.vue?vue&type=style&index=1'

   script.render = render
   export default script
   ```

   Notice how the code is importing `source.vue` itself, but with different request queries for each block.

2. We want the content in `script` block to be treated like `.js` files (and if it's `<script lang="ts">`, we want to to be treated like `.ts` files). Same for other language blocks. So we want webpack to apply any configured module rules that matches `.js` also to requests that look like `source.vue?vue&type=script`. This is what `VueLoaderPlugin` (`src/plugins.ts`) does: for each module rule in the webpack config, it creates a modified clone that targets corresponding Vue language block requests.

   Suppose we have configured `babel-loader` for all `*.js` files. That rule will be cloned and applied to Vue SFC `<script>` blocks as well. Internally to webpack, a request like

   ```js
   import script from 'source.vue?vue&type=script'
   ```

   Will expand to:

   ```js
   import script from 'babel-loader!vue-loader!source.vue?vue&type=script'
   ```

   Notice the `vue-loader` is also matched because `vue-loader` are applied to `.vue` files.

   Similarly, if you have configured `style-loader` + `css-loader` + `sass-loader` for `*.scss` files:

   ```html
   <style scoped lang="scss">
   ```

   Will be returned by `vue-loader` as:

   ```js
   import 'source.vue?vue&type=style&index=1&scoped&lang=scss'
   ```

   And webpack will expand it to:

   ```js
   import 'style-loader!css-loader!sass-loader!vue-loader!source.vue?vue&type=style&index=1&scoped&lang=scss'
   ```

3. When processing the expanded requests, the main `vue-loader` will get invoked again. This time though, the loader notices that the request has queries and is targeting a specific block only. So it selects (`src/select.ts`) the inner content of the target block and passes it on to the loaders matched after it.

4. For the `<script>` block, this is pretty much it. For `<template>` and `<style>` blocks though, a few extra tasks need to be performed:

   - We need to compile the template using the Vue template compiler;
   - We need to post-process the CSS in `<style scoped>` blocks, **after** `css-loader` but **before** `style-loader`.

   Technically, these are additional loaders (`src/templateLoader.ts` and `src/stylePostLoader.ts`) that need to be injected into the expanded loader chain. It would be very complicated if the end users have to configure this themselves, so `VueLoaderPlugin` also injects a global [Pitching Loader](https://webpack.js.org/api/loaders/#pitching-loader) (`src/pitcher.ts`) that intercepts Vue `<template>` and `<style>` requests and injects the necessary loaders. The final requests look like the following:

   ```js
   // <template lang="pug">
   import 'vue-loader/template-loader!pug-loader!source.vue?vue&type=template'

   // <style scoped lang="scss">
   import 'style-loader!vue-loader/style-post-loader!css-loader!sass-loader!vue-loader!source.vue?vue&type=style&index=1&scoped&lang=scss'
   ```


code:
declare module 'vue/compiler-sfc' {
    interface SFCDescriptor {
        id: string;
    }
}
import * as _compiler from 'vue/compiler-sfc';
export declare let compiler: typeof _compiler;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compiler = void 0;
try {
    // Vue 3.2.13+ ships the SFC compiler directly under the `vue` package
    // making it no longer necessary to have @vue/compiler-sfc separately installed.
    exports.compiler = require('vue/compiler-sfc');
}
catch (e) {
    try {
        exports.compiler = require('@vue/compiler-sfc');
    }
    catch (e) {
        throw new Error(`@vitejs/plugin-vue requires vue (>=3.2.13) or @vue/compiler-sfc ` +
            `to be present in the dependency tree.`);
    }
}


code: export declare function genCSSModulesCode(id: string, index: number, request: string, moduleName: string | boolean, needsHotReload: boolean): string;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genCSSModulesCode = void 0;
function genCSSModulesCode(id, index, request, moduleName, needsHotReload) {
    const styleVar = `style${index}`;
    let code = `\nimport ${styleVar} from ${request}`;
    // inject variable
    const name = typeof moduleName === 'string' ? moduleName : '$style';
    code += `\ncssModules["${name}"] = ${styleVar}`;
    if (needsHotReload) {
        code += `
if (module.hot) {
  module.hot.accept(${request}, () => {
    cssModules["${name}"] = ${styleVar}
    __VUE_HMR_RUNTIME__.rerender("${id}")
  })
}`;
    }
    return code;
}
exports.genCSSModulesCode = genCSSModulesCode;


code:
import type { CompilerOptions, SFCDescriptor } from 'vue/compiler-sfc';
export declare const descriptorCache: Map<string, SFCDescriptor>;
export declare function setDescriptor(filename: string, entry: SFCDescriptor): void;
export declare function getDescriptor(filename: string, compilerOptions?: CompilerOptions): SFCDescriptor;


code:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDescriptor = exports.setDescriptor = exports.descriptorCache = void 0;
const fs = __importStar(require("fs"));
const compiler_1 = require("./compiler");
const { parse } = compiler_1.compiler;
exports.descriptorCache = new Map();
function setDescriptor(filename, entry) {
    exports.descriptorCache.set(cleanQuery(filename), entry);
}
exports.setDescriptor = setDescriptor;
function getDescriptor(filename, compilerOptions) {
    filename = cleanQuery(filename);
    if (exports.descriptorCache.has(filename)) {
        return exports.descriptorCache.get(filename);
    }
    // This function should only be called after the descriptor has been
    // cached by the main loader.
    // If this is somehow called without a cache hit, it's probably due to sub
    // loaders being run in separate threads. The only way to deal with this is to
    // read from disk directly...
    const source = fs.readFileSync(filename, 'utf-8');
    const { descriptor } = parse(source, {
        filename,
        sourceMap: true,
        templateParseOptions: compilerOptions,
    });
    exports.descriptorCache.set(filename, descriptor);
    return descriptor;
}
exports.getDescriptor = getDescriptor;
function cleanQuery(str) {
    const i = str.indexOf('?');
    return i > 0 ? str.slice(0, i) : str;
}


code:
declare const _default: (sfc: any, props: [string, string][]) => any;
export default _default;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// runtime helper for setting properties on components
// in a tree-shakable way
exports.default = (sfc, props) => {
    const target = sfc.__vccOpts || sfc;
    for (const [key, val] of props) {
        target[key] = val;
    }
    return target;
};


code:
import type { CompilerError } from 'vue/compiler-sfc';
export declare function formatError(err: SyntaxError | CompilerError, source: string, file: string): void;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatError = void 0;
const compiler_1 = require("./compiler");
const chalk = require("chalk");
const { generateCodeFrame } = compiler_1.compiler;
function formatError(err, source, file) {
    const loc = err.loc;
    if (!loc) {
        return;
    }
    const locString = `:${loc.start.line}:${loc.start.column}`;
    const filePath = chalk.gray(`at ${file}${locString}`);
    const codeframe = generateCodeFrame(source, loc.start.offset, loc.end.offset);
    err.message = `\n${chalk.red(`VueCompilerError: ${err.message}`)}\n${filePath}\n${chalk.yellow(codeframe)}\n`;
}
exports.formatError = formatError;


code: export declare function genHotReloadCode(id: string, templateRequest: string | undefined): string;


code:
"use strict";
// __VUE_HMR_RUNTIME__ is injected to global scope by @vue/runtime-core
Object.defineProperty(exports, "__esModule", { value: true });
exports.genHotReloadCode = void 0;
function genHotReloadCode(id, templateRequest) {
    return `
/* hot reload */
if (module.hot) {
  __exports__.__hmrId = "${id}"
  const api = __VUE_HMR_RUNTIME__
  module.hot.accept()
  if (!api.createRecord('${id}', __exports__)) {
    api.reload('${id}', __exports__)
  }
  ${templateRequest ? genTemplateHotReloadCode(id, templateRequest) : ''}
}
`;
}
exports.genHotReloadCode = genHotReloadCode;
function genTemplateHotReloadCode(id, request) {
    return `
  module.hot.accept(${request}, () => {
    api.rerender('${id}', render)
  })
`;
}


code:
import type { LoaderContext } from 'webpack';
import type { TemplateCompiler, CompilerOptions, SFCTemplateCompileOptions, SFCScriptCompileOptions } from 'vue/compiler-sfc';
import VueLoaderPlugin from './plugin';
export { VueLoaderPlugin };
export interface VueLoaderOptions {
    babelParserPlugins?: SFCScriptCompileOptions['babelParserPlugins'];
    transformAssetUrls?: SFCTemplateCompileOptions['transformAssetUrls'];
    compiler?: TemplateCompiler | string;
    compilerOptions?: CompilerOptions;
    /**
     * TODO remove in 3.4
     * @deprecated
     */
    reactivityTransform?: boolean;
    /**
     * @experimental
     */
    propsDestructure?: boolean;
    /**
     * @experimental
     */
    defineModel?: boolean;
    customElement?: boolean | RegExp;
    hotReload?: boolean;
    exposeFilename?: boolean;
    appendExtension?: boolean;
    enableTsInTemplate?: boolean;
    experimentalInlineMatchResource?: boolean;
    isServerBuild?: boolean;
}
export default function loader(this: LoaderContext<VueLoaderOptions>, source: string): string | void;


code:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VueLoaderPlugin = void 0;
const path = __importStar(require("path"));
const qs = __importStar(require("querystring"));
const hash = require("hash-sum");
const compiler_1 = require("./compiler");
const select_1 = require("./select");
const hotReload_1 = require("./hotReload");
const cssModules_1 = require("./cssModules");
const formatError_1 = require("./formatError");
const plugin_1 = __importDefault(require("./plugin"));
exports.VueLoaderPlugin = plugin_1.default;
const resolveScript_1 = require("./resolveScript");
const descriptorCache_1 = require("./descriptorCache");
const util_1 = require("./util");
let errorEmitted = false;
const { parse } = compiler_1.compiler;
const exportHelperPath = require.resolve('./exportHelper');
function loader(source) {
    var _a;
    const loaderContext = this;
    // check if plugin is installed
    if (!errorEmitted &&
        !loaderContext['thread-loader'] &&
        !loaderContext[plugin_1.default.NS]) {
        loaderContext.emitError(new Error(`vue-loader was used without the corresponding plugin. ` +
            `Make sure to include VueLoaderPlugin in your webpack config.`));
        errorEmitted = true;
    }
    const stringifyRequest = (r) => (0, util_1.stringifyRequest)(loaderContext, r);
    const { mode, target, sourceMap, rootContext, resourcePath, resourceQuery: _resourceQuery = '', _compiler, } = loaderContext;
    const isWebpack5 = (0, util_1.testWebpack5)(_compiler);
    const rawQuery = _resourceQuery.slice(1);
    const incomingQuery = qs.parse(rawQuery);
    const resourceQuery = rawQuery ? `&${rawQuery}` : '';
    const options = ((0, util_1.getOptions)(loaderContext) || {});
    const enableInlineMatchResource = isWebpack5 && Boolean(options.experimentalInlineMatchResource);
    const isServer = (_a = options.isServerBuild) !== null && _a !== void 0 ? _a : target === 'node';
    const isProduction = mode === 'production' || process.env.NODE_ENV === 'production';
    const filename = resourcePath.replace(/\?.*$/, '');
    const { descriptor, errors } = parse(source, {
        filename,
        sourceMap,
        templateParseOptions: options.compilerOptions,
    });
    const asCustomElement = typeof options.customElement === 'boolean'
        ? options.customElement
        : (options.customElement || /\.ce\.vue$/).test(filename);
    // cache descriptor
    (0, descriptorCache_1.setDescriptor)(filename, descriptor);
    if (errors.length) {
        errors.forEach((err) => {
            (0, formatError_1.formatError)(err, source, resourcePath);
            loaderContext.emitError(err);
        });
        return ``;
    }
    // module id for scoped CSS & hot-reload
    const rawShortFilePath = path
        .relative(rootContext || process.cwd(), filename)
        .replace(/^(\.\.[\/\\])+/, '');
    const shortFilePath = rawShortFilePath.replace(/\\/g, '/');
    const id = hash(isProduction
        ? shortFilePath + '\n' + source.replace(/\r\n/g, '\n')
        : shortFilePath);
    // if the query has a type field, this is a language block request
    // e.g. foo.vue?type=template&id=xxxxx
    // and we will return early
    if (incomingQuery.type) {
        return (0, select_1.selectBlock)(descriptor, id, options, loaderContext, incomingQuery, !!options.appendExtension);
    }
    // feature information
    const hasScoped = descriptor.styles.some((s) => s.scoped);
    const needsHotReload = !isServer &&
        !isProduction &&
        !!(descriptor.script || descriptor.scriptSetup || descriptor.template) &&
        options.hotReload !== false;
    // extra properties to attach to the script object
    // we need to do this in a tree-shaking friendly manner
    const propsToAttach = [];
    // script
    let scriptImport = `const script = {}`;
    let isTS = false;
    const { script, scriptSetup } = descriptor;
    if (script || scriptSetup) {
        const lang = (script === null || script === void 0 ? void 0 : script.lang) || (scriptSetup === null || scriptSetup === void 0 ? void 0 : scriptSetup.lang);
        isTS = !!(lang && /tsx?/.test(lang));
        const externalQuery = Boolean(script && !scriptSetup && script.src)
            ? `&external`
            : ``;
        const src = (script && !scriptSetup && script.src) || resourcePath;
        const attrsQuery = attrsToQuery((scriptSetup || script).attrs, 'js');
        const query = `?vue&type=script${attrsQuery}${resourceQuery}${externalQuery}`;
        let scriptRequest;
        if (enableInlineMatchResource) {
            scriptRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, lang || 'js'));
        }
        else {
            scriptRequest = stringifyRequest(src + query);
        }
        scriptImport =
            `import script from ${scriptRequest}\n` +
                // support named exports
                `export * from ${scriptRequest}`;
    }
    // template
    let templateImport = ``;
    let templateRequest;
    const renderFnName = isServer ? `ssrRender` : `render`;
    const useInlineTemplate = (0, resolveScript_1.canInlineTemplate)(descriptor, isProduction);
    if (descriptor.template && !useInlineTemplate) {
        const src = descriptor.template.src || resourcePath;
        const externalQuery = Boolean(descriptor.template.src) ? `&external` : ``;
        const idQuery = `&id=${id}`;
        const scopedQuery = hasScoped ? `&scoped=true` : ``;
        const attrsQuery = attrsToQuery(descriptor.template.attrs);
        const tsQuery = options.enableTsInTemplate !== false && isTS ? `&ts=true` : ``;
        const query = `?vue&type=template${idQuery}${scopedQuery}${tsQuery}${attrsQuery}${resourceQuery}${externalQuery}`;
        if (enableInlineMatchResource) {
            templateRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, options.enableTsInTemplate !== false && isTS ? 'ts' : 'js'));
        }
        else {
            templateRequest = stringifyRequest(src + query);
        }
        templateImport = `import { ${renderFnName} } from ${templateRequest}`;
        propsToAttach.push([renderFnName, renderFnName]);
    }
    // styles
    let stylesCode = ``;
    let hasCSSModules = false;
    const nonWhitespaceRE = /\S+/;
    if (descriptor.styles.length) {
        descriptor.styles
            .filter((style) => style.src || nonWhitespaceRE.test(style.content))
            .forEach((style, i) => {
            const src = style.src || resourcePath;
            const attrsQuery = attrsToQuery(style.attrs, 'css');
            const lang = String(style.attrs.lang || 'css');
            // make sure to only pass id when necessary so that we don't inject
            // duplicate tags when multiple components import the same css file
            const idQuery = !style.src || style.scoped ? `&id=${id}` : ``;
            const inlineQuery = asCustomElement ? `&inline` : ``;
            const externalQuery = Boolean(style.src) ? `&external` : ``;
            const query = `?vue&type=style&index=${i}${idQuery}${inlineQuery}${attrsQuery}${resourceQuery}${externalQuery}`;
            let styleRequest;
            if (enableInlineMatchResource) {
                styleRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, lang));
            }
            else {
                styleRequest = stringifyRequest(src + query);
            }
            if (style.module) {
                if (asCustomElement) {
                    loaderContext.emitError(new Error(`<style module> is not supported in custom element mode.`));
                }
                if (!hasCSSModules) {
                    stylesCode += `\nconst cssModules = {}`;
                    propsToAttach.push([`__cssModules`, `cssModules`]);
                    hasCSSModules = true;
                }
                stylesCode += (0, cssModules_1.genCSSModulesCode)(id, i, styleRequest, style.module, needsHotReload);
            }
            else {
                if (asCustomElement) {
                    stylesCode += `\nimport _style_${i} from ${styleRequest}`;
                }
                else {
                    stylesCode += `\nimport ${styleRequest}`;
                }
            }
            // TODO SSR critical CSS collection
        });
        if (asCustomElement) {
            propsToAttach.push([
                `styles`,
                `[${descriptor.styles.map((_, i) => `_style_${i}`)}]`,
            ]);
        }
    }
    let code = [templateImport, scriptImport, stylesCode]
        .filter(Boolean)
        .join('\n');
    // attach scope Id for runtime use
    if (hasScoped) {
        propsToAttach.push([`__scopeId`, `"data-v-${id}"`]);
    }
    // Expose filename. This is used by the devtools and Vue runtime warnings.
    if (!isProduction) {
        // Expose the file's full path in development, so that it can be opened
        // from the devtools.
        propsToAttach.push([
            `__file`,
            JSON.stringify(rawShortFilePath.replace(/\\/g, '/')),
        ]);
    }
    else if (options.exposeFilename) {
        // Libraries can opt-in to expose their components' filenames in production builds.
        // For security reasons, only expose the file's basename in production.
        propsToAttach.push([`__file`, JSON.stringify(path.basename(resourcePath))]);
    }
    // custom blocks
    if (descriptor.customBlocks && descriptor.customBlocks.length) {
        code += `\n/* custom blocks */\n`;
        code +=
            descriptor.customBlocks
                .map((block, i) => {
                const src = block.attrs.src || resourcePath;
                const attrsQuery = attrsToQuery(block.attrs);
                const blockTypeQuery = `&blockType=${qs.escape(block.type)}`;
                const issuerQuery = block.attrs.src
                    ? `&issuerPath=${qs.escape(resourcePath)}`
                    : '';
                const externalQuery = Boolean(block.attrs.src) ? `&external` : ``;
                const query = `?vue&type=custom&index=${i}${blockTypeQuery}${issuerQuery}${attrsQuery}${resourceQuery}${externalQuery}`;
                let customRequest;
                if (enableInlineMatchResource) {
                    customRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, block.attrs.lang));
                }
                else {
                    customRequest = stringifyRequest(src + query);
                }
                return (`import block${i} from ${customRequest}\n` +
                    `if (typeof block${i} === 'function') block${i}(script)`);
            })
                .join(`\n`) + `\n`;
    }
    // finalize
    if (!propsToAttach.length) {
        code += `\n\nconst __exports__ = script;`;
    }
    else {
        code += `\n\nimport exportComponent from ${stringifyRequest(exportHelperPath)}`;
        code += `\nconst __exports__ = /*#__PURE__*/exportComponent(script, [${propsToAttach
            .map(([key, val]) => `['${key}',${val}]`)
            .join(',')}])`;
    }
    if (needsHotReload) {
        code += (0, hotReload_1.genHotReloadCode)(id, templateRequest);
    }
    code += `\n\nexport default __exports__`;
    return code;
}
exports.default = loader;
// these are built-in query parameters so should be ignored
// if the user happen to add them as attrs
const ignoreList = ['id', 'index', 'src', 'type'];
function attrsToQuery(attrs, langFallback) {
    let query = ``;
    for (const name in attrs) {
        const value = attrs[name];
        if (!ignoreList.includes(name)) {
            query += `&${qs.escape(name)}=${value ? qs.escape(String(value)) : ``}`;
        }
    }
    if (langFallback && !(`lang` in attrs)) {
        query += `&lang=${langFallback}`;
    }
    return query;
}


code:
import type { LoaderDefinitionFunction } from 'webpack';
declare const pitcher: LoaderDefinitionFunction;
export declare const pitch: () => string | undefined;
export default pitcher;


code:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.pitch = void 0;
const qs = __importStar(require("querystring"));
const util_1 = require("./util");
const selfPath = require.resolve('./index');
// const templateLoaderPath = require.resolve('./templateLoader')
const stylePostLoaderPath = require.resolve('./stylePostLoader');
const styleInlineLoaderPath = require.resolve('./styleInlineLoader');
const isESLintLoader = (l) => /(\/|\\|@)eslint-loader/.test(l.path);
const isNullLoader = (l) => /(\/|\\|@)null-loader/.test(l.path);
const isCSSLoader = (l) => /(\/|\\|@)css-loader/.test(l.path);
const isCacheLoader = (l) => /(\/|\\|@)cache-loader/.test(l.path);
const isNotPitcher = (l) => l.path !== __filename;
const pitcher = (code) => code;
// This pitching loader is responsible for intercepting all vue block requests
// and transform it into appropriate requests.
const pitch = function () {
    var _a;
    const context = this;
    const rawLoaders = context.loaders.filter(isNotPitcher);
    let loaders = rawLoaders;
    // do not inject if user uses null-loader to void the type (#1239)
    if (loaders.some(isNullLoader)) {
        return;
    }
    const query = qs.parse(context.resourceQuery.slice(1));
    const isInlineBlock = /\.vue$/.test(context.resourcePath);
    // eslint-loader may get matched multiple times
    // if this is an inline block, since the whole file itself is being linted,
    // remove eslint-loader to avoid duplicate linting.
    if (isInlineBlock) {
        loaders = loaders.filter((l) => !isESLintLoader(l));
    }
    // Important: dedupe loaders since both the original rule
    // and the cloned rule would match a source import request or a
    // resourceQuery-only rule that intends to target a custom block with no lang
    const seen = new Map();
    loaders = loaders.filter((loader) => {
        const identifier = typeof loader === 'string'
            ? loader
            : // Dedupe based on both path and query if available. This is important
                // in Vue CLI so that postcss-loaders with different options can co-exist
                loader.path + loader.query;
        if (!seen.has(identifier)) {
            seen.set(identifier, true);
            return true;
        }
    });
    // Inject style-post-loader before css-loader for scoped CSS and trimming
    const isWebpack5 = (0, util_1.testWebpack5)(context._compiler);
    const options = ((0, util_1.getOptions)(context) || {});
    if (query.type === `style`) {
        if (isWebpack5 && ((_a = context._compiler) === null || _a === void 0 ? void 0 : _a.options.experiments.css)) {
            // If user enables `experiments.css`, then we are trying to emit css code directly.
            // Although we can target requests like `xxx.vue?type=style` to match `type: "css"`,
            // it will make the plugin a mess.
            if (!options.experimentalInlineMatchResource) {
                context.emitError(new Error('`experimentalInlineMatchResource` should be enabled if `experiments.css` enabled currently'));
                return '';
            }
            if (query.inline || query.module) {
                context.emitError(new Error('`inline` or `module` is currently not supported with `experiments.css` enabled'));
                return '';
            }
            const loaderString = [stylePostLoaderPath, ...loaders]
                .map((loader) => {
                return typeof loader === 'string' ? loader : loader.request;
            })
                .join('!');
            const styleRequest = (0, util_1.stringifyRequest)(context, `${context.resourcePath}${query.lang ? `.${query.lang}` : ''}${context.resourceQuery}!=!-!${loaderString}!${context.resource}`);
            return `@import ${styleRequest};`;
        }
        const cssLoaderIndex = loaders.findIndex(isCSSLoader);
        if (cssLoaderIndex > -1) {
            // if inlined, ignore any loaders after css-loader and replace w/ inline
            // loader
            const afterLoaders = query.inline != null
                ? [styleInlineLoaderPath]
                : loaders.slice(0, cssLoaderIndex + 1);
            const beforeLoaders = loaders.slice(cssLoaderIndex + 1);
            return genProxyModule([...afterLoaders, stylePostLoaderPath, ...beforeLoaders], context, !!query.module || query.inline != null, query.lang || 'css');
        }
    }
    // if a custom block has no other matching loader other than vue-loader itself
    // or cache-loader, we should ignore it
    if (query.type === `custom` && shouldIgnoreCustomBlock(loaders)) {
        return ``;
    }
    // Rewrite request. Technically this should only be done when we have deduped
    // loaders. But somehow this is required for block source maps to work.
    return genProxyModule(loaders, context, query.type !== 'template', query.ts ? 'ts' : query.lang);
};
exports.pitch = pitch;
function genProxyModule(loaders, context, exportDefault = true, lang = 'js') {
    const request = genRequest(loaders, lang, context);
    // return a proxy module which simply re-exports everything from the
    // actual request. Note for template blocks the compiled module has no
    // default export.
    return ((exportDefault ? `export { default } from ${request}; ` : ``) +
        `export * from ${request}`);
}
function genRequest(loaders, lang, context) {
    const isWebpack5 = (0, util_1.testWebpack5)(context._compiler);
    const options = ((0, util_1.getOptions)(context) || {});
    const enableInlineMatchResource = isWebpack5 && options.experimentalInlineMatchResource;
    const loaderStrings = loaders.map((loader) => {
        return typeof loader === 'string' ? loader : loader.request;
    });
    const resource = context.resourcePath + context.resourceQuery;
    if (enableInlineMatchResource) {
        return (0, util_1.stringifyRequest)(context, `${context.resourcePath}${lang ? `.${lang}` : ''}${context.resourceQuery}!=!-!${[...loaderStrings, resource].join('!')}`);
    }
    return (0, util_1.stringifyRequest)(context, '-!' + [...loaderStrings, resource].join('!'));
}
function shouldIgnoreCustomBlock(loaders) {
    const actualLoaders = loaders.filter((loader) => {
        // vue-loader
        if (loader.path === selfPath) {
            return false;
        }
        // cache-loader
        if (isCacheLoader(loader)) {
            return false;
        }
        return true;
    });
    return actualLoaders.length === 0;
}
exports.default = pitcher;


code:
import type { Compiler } from 'webpack';
declare class Plugin {
    static NS: string;
    apply(compiler: Compiler): void;
}
export default Plugin;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("./util");
const NS = 'vue-loader';
class Plugin {
    apply(compiler) {
        let Ctor;
        if ((0, util_1.testWebpack5)(compiler)) {
            // webpack5 and upper
            Ctor = require('./pluginWebpack5').default;
        }
        else {
            // webpack4 and lower
            Ctor = require('./pluginWebpack4').default;
        }
        new Ctor().apply(compiler);
    }
}
Plugin.NS = NS;
exports.default = Plugin;


code:
import type { Compiler } from 'webpack';
declare class VueLoaderPlugin {
    static NS: string;
    apply(compiler: Compiler): void;
}
export default VueLoaderPlugin;


code:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const qs = __importStar(require("querystring"));
const resolveScript_1 = require("./resolveScript");
const fs = require("fs");
const compiler_1 = require("./compiler");
const descriptorCache_1 = require("./descriptorCache");
const util_1 = require("./util");
const RuleSet = require('webpack/lib/RuleSet');
const id = 'vue-loader-plugin';
const NS = 'vue-loader';
class VueLoaderPlugin {
    apply(compiler) {
        // inject NS for plugin installation check in the main loader
        compiler.hooks.compilation.tap(id, (compilation) => {
            compilation.hooks.normalModuleLoader.tap(id, (loaderContext) => {
                loaderContext[NS] = true;
            });
        });
        const rawRules = compiler.options.module.rules;
        // use webpack's RuleSet utility to normalize user rules
        const rules = new RuleSet(rawRules).rules;
        // find the rule that applies to vue files
        let vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue`));
        if (vueRuleIndex < 0) {
            vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue.html`));
        }
        const vueRule = rules[vueRuleIndex];
        if (!vueRule) {
            throw new Error(`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +
                `Make sure there is at least one root-level rule that matches .vue or .vue.html files.`);
        }
        if (vueRule.oneOf) {
            throw new Error(`[VueLoaderPlugin Error] vue-loader currently does not support vue rules with oneOf.`);
        }
        // get the normlized "use" for vue files
        const vueUse = vueRule.use;
        // get vue-loader options
        const vueLoaderUseIndex = vueUse.findIndex((u) => {
            // FIXME: this code logic is incorrect when project paths starts with `vue-loader-something`
            return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader || '');
        });
        if (vueLoaderUseIndex < 0) {
            throw new Error(`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +
                `Make sure the rule matching .vue files include vue-loader in its use.`);
        }
        const vueLoaderUse = vueUse[vueLoaderUseIndex];
        const vueLoaderOptions = (vueLoaderUse.options =
            vueLoaderUse.options || {});
        // for each user rule (except the vue rule), create a cloned rule
        // that targets the corresponding language blocks in *.vue files.
        const clonedRules = rules.filter((r) => r !== vueRule).map(cloneRule);
        // rule for template compiler
        const templateCompilerRule = {
            loader: require.resolve('./templateLoader'),
            resourceQuery: (query) => {
                const parsed = qs.parse(query.slice(1));
                return parsed.vue != null && parsed.type === 'template';
            },
            options: Object.assign({ ident: vueLoaderUse.ident }, vueLoaderOptions),
        };
        // for each rule that matches plain .js/.ts files, also create a clone and
        // match it against the compiled template code inside *.vue files, so that
        // compiled vue render functions receive the same treatment as user code
        // (mostly babel)
        const matchesJS = createMatcher(`test.js`);
        const matchesTS = createMatcher(`test.ts`);
        const jsRulesForRenderFn = rules
            .filter((r) => r !== vueRule && (matchesJS(r) || matchesTS(r)))
            .map(cloneRuleForRenderFn);
        // pitcher for block requests (for injecting stylePostLoader and deduping
        // loaders matched for src imports)
        const pitcher = {
            loader: require.resolve('./pitcher'),
            resourceQuery: (query) => {
                const parsed = qs.parse(query.slice(1));
                return parsed.vue != null;
            },
        };
        // replace original rules
        compiler.options.module.rules = [
            pitcher,
            ...jsRulesForRenderFn,
            templateCompilerRule,
            ...clonedRules,
            ...rules,
        ];
        // 3.3 HMR support for imported types
        if ((0, util_1.needHMR)(vueLoaderOptions, compiler.options) &&
            compiler_1.compiler.invalidateTypeCache) {
            let watcher;
            const WatchPack = require('watchpack');
            compiler.hooks.afterCompile.tap(id, (compilation) => {
                if (compilation.compiler === compiler) {
                    // type-only imports can be tree-shaken and not registered as a
                    // watched file at all, so we have to manually ensure they are watched.
                    const files = [...resolveScript_1.typeDepToSFCMap.keys()];
                    const oldWatcher = watcher;
                    watcher = new WatchPack({ aggregateTimeout: 0 });
                    watcher.once('aggregated', (changes, removals) => {
                        for (const file of changes) {
                            // bust compiler-sfc type dep cache
                            compiler_1.compiler.invalidateTypeCache(file);
                            const affectedSFCs = resolveScript_1.typeDepToSFCMap.get(file);
                            if (affectedSFCs) {
                                for (const sfc of affectedSFCs) {
                                    // bust script resolve cache
                                    const desc = descriptorCache_1.descriptorCache.get(sfc);
                                    if (desc)
                                        resolveScript_1.clientCache.delete(desc);
                                    // force update importing SFC
                                    fs.writeFileSync(sfc, fs.readFileSync(sfc, 'utf-8'));
                                }
                            }
                        }
                        for (const file of removals) {
                            compiler_1.compiler.invalidateTypeCache(file);
                        }
                    });
                    watcher.watch({ files, startTime: Date.now() });
                    if (oldWatcher) {
                        oldWatcher.close();
                    }
                }
            });
            compiler.hooks.watchClose.tap(id, () => {
                if (watcher) {
                    watcher.close();
                }
            });
            // In some cases, e.g. in this project's tests,
            // even though needsHMR() returns true, webpack is not watching, thus no watchClose hook is called.
            // So we need to close the watcher when webpack is done.
            compiler.hooks.done.tap(id, () => {
                if (watcher) {
                    watcher.close();
                }
            });
        }
    }
}
VueLoaderPlugin.NS = NS;
function createMatcher(fakeFile) {
    return (rule) => {
        // #1201 we need to skip the `include` check when locating the vue rule
        const clone = Object.assign({}, rule);
        delete clone.include;
        const normalized = RuleSet.normalizeRule(clone, {}, '');
        return !rule.enforce && normalized.resource && normalized.resource(fakeFile);
    };
}
function cloneRule(rule) {
    const resource = rule.resource;
    const resourceQuery = rule.resourceQuery;
    // Assuming `test` and `resourceQuery` tests are executed in series and
    // synchronously (which is true based on RuleSet's implementation), we can
    // save the current resource being matched from `test` so that we can access
    // it in `resourceQuery`. This ensures when we use the normalized rule's
    // resource check, include/exclude are matched correctly.
    let currentResource;
    const res = Object.assign(Object.assign({}, rule), { resource: (resource) => {
            currentResource = resource;
            return true;
        }, resourceQuery: (query) => {
            const parsed = qs.parse(query.slice(1));
            if (parsed.vue == null) {
                return false;
            }
            if (resource && parsed.lang == null) {
                return false;
            }
            const fakeResourcePath = `${currentResource}.${parsed.lang}`;
            if (resource && !resource(fakeResourcePath)) {
                return false;
            }
            if (resourceQuery && !resourceQuery(query)) {
                return false;
            }
            return true;
        } });
    if (rule.rules) {
        res.rules = rule.rules.map(cloneRule);
    }
    if (rule.oneOf) {
        res.oneOf = rule.oneOf.map(cloneRule);
    }
    return res;
}
function cloneRuleForRenderFn(rule) {
    const resource = rule.resource;
    const resourceQuery = rule.resourceQuery;
    let currentResource;
    const res = Object.assign(Object.assign({}, rule), { resource: (resource) => {
            currentResource = resource;
            return true;
        }, resourceQuery: (query) => {
            const parsed = qs.parse(query.slice(1));
            if (parsed.vue == null || parsed.type !== 'template') {
                return false;
            }
            const fakeResourcePath = `${currentResource}.${parsed.ts ? `ts` : `js`}`;
            if (resource && !resource(fakeResourcePath)) {
                return false;
            }
            if (resourceQuery && !resourceQuery(query)) {
                return false;
            }
            return true;
        } });
    if (rule.rules) {
        res.rules = rule.rules.map(cloneRuleForRenderFn);
    }
    if (rule.oneOf) {
        res.oneOf = rule.oneOf.map(cloneRuleForRenderFn);
    }
    return res;
}
exports.default = VueLoaderPlugin;


code:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const qs = __importStar(require("querystring"));
const util_1 = require("./util");
const resolveScript_1 = require("./resolveScript");
const compiler_1 = require("./compiler");
const descriptorCache_1 = require("./descriptorCache");
const id = 'vue-loader-plugin';
const NS = 'vue-loader';
const NormalModule = require('webpack/lib/NormalModule');
const BasicEffectRulePlugin = require('webpack/lib/rules/BasicEffectRulePlugin');
const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin');
const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin');
const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler');
let objectMatcherRulePlugins = [];
try {
    const ObjectMatcherRulePlugin = require('webpack/lib/rules/ObjectMatcherRulePlugin');
    objectMatcherRulePlugins.push(new ObjectMatcherRulePlugin('assert', 'assertions'), new ObjectMatcherRulePlugin('descriptionData'));
}
catch (e) {
    const DescriptionDataMatcherRulePlugin = require('webpack/lib/rules/DescriptionDataMatcherRulePlugin');
    objectMatcherRulePlugins.push(new DescriptionDataMatcherRulePlugin());
}
const ruleSetCompiler = new RuleSetCompiler([
    new BasicMatcherRulePlugin('test', 'resource'),
    new BasicMatcherRulePlugin('mimetype'),
    new BasicMatcherRulePlugin('dependency'),
    new BasicMatcherRulePlugin('include', 'resource'),
    new BasicMatcherRulePlugin('exclude', 'resource', true),
    new BasicMatcherRulePlugin('conditions'),
    new BasicMatcherRulePlugin('resource'),
    new BasicMatcherRulePlugin('resourceQuery'),
    new BasicMatcherRulePlugin('resourceFragment'),
    new BasicMatcherRulePlugin('realResource'),
    new BasicMatcherRulePlugin('issuer'),
    new BasicMatcherRulePlugin('compiler'),
    new BasicMatcherRulePlugin('issuerLayer'),
    ...objectMatcherRulePlugins,
    new BasicEffectRulePlugin('type'),
    new BasicEffectRulePlugin('sideEffects'),
    new BasicEffectRulePlugin('parser'),
    new BasicEffectRulePlugin('resolve'),
    new BasicEffectRulePlugin('generator'),
    new BasicEffectRulePlugin('layer'),
    new UseEffectRulePlugin(),
]);
class VueLoaderPlugin {
    apply(compiler) {
        // @ts-ignore
        const normalModule = compiler.webpack.NormalModule || NormalModule;
        // add NS marker so that the loader can detect and report missing plugin
        compiler.hooks.compilation.tap(id, (compilation) => {
            normalModule
                .getCompilationHooks(compilation)
                .loader.tap(id, (loaderContext) => {
                loaderContext[NS] = true;
            });
        });
        const rules = compiler.options.module.rules;
        let rawVueRule;
        let vueRules = [];
        for (const rawRule of rules) {
            // skip rules with 'enforce'. eg. rule for eslint-loader
            if (rawRule.enforce) {
                continue;
            }
            vueRules = match(rawRule, 'foo.vue');
            if (!vueRules.length) {
                vueRules = match(rawRule, 'foo.vue.html');
            }
            if (vueRules.length > 0) {
                if (rawRule.oneOf) {
                    throw new Error(`[VueLoaderPlugin Error] vue-loader currently does not support vue rules with oneOf.`);
                }
                rawVueRule = rawRule;
                break;
            }
        }
        if (!vueRules.length) {
            throw new Error(`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +
                `Make sure there is at least one root-level rule that matches .vue or .vue.html files.`);
        }
        // get the normalized "use" for vue files
        const vueUse = vueRules
            .filter((rule) => rule.type === 'use')
            .map((rule) => rule.value);
        // get vue-loader options
        const vueLoaderUseIndex = vueUse.findIndex((u) => {
            // FIXME: this code logic is incorrect when project paths starts with `vue-loader-something`
            return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader);
        });
        if (vueLoaderUseIndex < 0) {
            throw new Error(`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +
                `Make sure the rule matching .vue files include vue-loader in its use.`);
        }
        // make sure vue-loader options has a known ident so that we can share
        // options by reference in the template-loader by using a ref query like
        // template-loader??vue-loader-options
        const vueLoaderUse = vueUse[vueLoaderUseIndex];
        const vueLoaderOptions = (vueLoaderUse.options =
            vueLoaderUse.options || {});
        const enableInlineMatchResource = vueLoaderOptions.experimentalInlineMatchResource;
        // for each user rule (except the vue rule), create a cloned rule
        // that targets the corresponding language blocks in *.vue files.
        const refs = new Map();
        const clonedRules = rules
            .filter((r) => r !== rawVueRule)
            .map((rawRule) => cloneRule(rawRule, refs, langBlockRuleCheck, langBlockRuleResource));
        // fix conflict with config.loader and config.options when using config.use
        delete rawVueRule.loader;
        delete rawVueRule.options;
        rawVueRule.use = vueUse;
        // rule for template compiler
        const templateCompilerRule = {
            loader: require.resolve('./templateLoader'),
            resourceQuery: (query) => {
                if (!query) {
                    return false;
                }
                const parsed = qs.parse(query.slice(1));
                return parsed.vue != null && parsed.type === 'template';
            },
            options: vueLoaderOptions,
        };
        // for each rule that matches plain .js files, also create a clone and
        // match it against the compiled template code inside *.vue files, so that
        // compiled vue render functions receive the same treatment as user code
        // (mostly babel)
        const jsRulesForRenderFn = rules
            .filter((r) => r !== rawVueRule &&
            (match(r, 'test.js').length > 0 || match(r, 'test.ts').length > 0))
            .map((rawRule) => cloneRule(rawRule, refs, jsRuleCheck, jsRuleResource));
        // global pitcher (responsible for injecting template compiler loader & CSS
        // post loader)
        const pitcher = {
            loader: require.resolve('./pitcher'),
            resourceQuery: (query) => {
                if (!query) {
                    return false;
                }
                const parsed = qs.parse(query.slice(1));
                return parsed.vue != null;
            },
            options: vueLoaderOptions,
        };
        // replace original rules
        if (enableInlineMatchResource) {
            // Match rules using `vue-loader`
            const vueLoaderRules = rules.filter((rule) => {
                const matchOnce = (use) => {
                    let loaderString = '';
                    if (!use) {
                        return loaderString;
                    }
                    if (typeof use === 'string') {
                        loaderString = use;
                    }
                    else if (Array.isArray(use)) {
                        loaderString = matchOnce(use[0]);
                    }
                    else if (typeof use === 'object' && use.loader) {
                        loaderString = use.loader;
                    }
                    return loaderString;
                };
                const loader = rule.loader || matchOnce(rule.use);
                return (loader === require('../package.json').name ||
                    loader.startsWith(require.resolve('./index')));
            });
            compiler.options.module.rules = [
                pitcher,
                ...rules.filter((rule) => !vueLoaderRules.includes(rule)),
                templateCompilerRule,
                ...clonedRules,
                ...vueLoaderRules,
            ];
        }
        else {
            compiler.options.module.rules = [
                pitcher,
                ...jsRulesForRenderFn,
                templateCompilerRule,
                ...clonedRules,
                ...rules,
            ];
        }
        // 3.3 HMR support for imported types
        if ((0, util_1.needHMR)(vueLoaderOptions, compiler.options) &&
            compiler_1.compiler.invalidateTypeCache) {
            compiler.hooks.afterCompile.tap(id, (compilation) => {
                if (compilation.compiler === compiler) {
                    for (const file of resolveScript_1.typeDepToSFCMap.keys()) {
                        compilation.fileDependencies.add(file);
                    }
                }
            });
            compiler.hooks.watchRun.tap(id, () => {
                if (!compiler.modifiedFiles)
                    return;
                for (const file of compiler.modifiedFiles) {
                    compiler_1.compiler.invalidateTypeCache(file);
                    const affectedSFCs = resolveScript_1.typeDepToSFCMap.get(file);
                    if (affectedSFCs) {
                        for (const sfc of affectedSFCs) {
                            // bust script resolve cache
                            const desc = descriptorCache_1.descriptorCache.get(sfc);
                            if (desc)
                                resolveScript_1.clientCache.delete(desc);
                            // force update importing SFC
                            // @ts-ignore
                            compiler.fileTimestamps.set(sfc, {
                                safeTime: Date.now(),
                                timestamp: Date.now(),
                            });
                        }
                    }
                }
                for (const file of compiler.removedFiles) {
                    compiler_1.compiler.invalidateTypeCache(file);
                }
            });
        }
    }
}
VueLoaderPlugin.NS = NS;
const matcherCache = new WeakMap();
function match(rule, fakeFile) {
    let ruleSet = matcherCache.get(rule);
    if (!ruleSet) {
        // skip the `include` check when locating the vue rule
        const clonedRawRule = Object.assign({}, rule);
        delete clonedRawRule.include;
        ruleSet = ruleSetCompiler.compile([clonedRawRule]);
        matcherCache.set(rule, ruleSet);
    }
    return ruleSet.exec({
        resource: fakeFile,
    });
}
const langBlockRuleCheck = (query, rule) => {
    return (query.type === 'custom' || !rule.conditions.length || query.lang != null);
};
const langBlockRuleResource = (query, resource) => `${resource}.${query.lang}`;
const jsRuleCheck = (query) => {
    return query.type === 'template';
};
const jsRuleResource = (query, resource) => `${resource}.${query.ts ? `ts` : `js`}`;
let uid = 0;
function cloneRule(rawRule, refs, ruleCheck, ruleResource) {
    const compiledRule = ruleSetCompiler.compileRule(`clonedRuleSet-${++uid}`, rawRule, refs);
    // do not process rule with enforce
    if (!rawRule.enforce) {
        const ruleUse = compiledRule.effects
            .filter((effect) => effect.type === 'use')
            .map((effect) => effect.value);
        // fix conflict with config.loader and config.options when using config.use
        delete rawRule.loader;
        delete rawRule.options;
        rawRule.use = ruleUse;
    }
    let currentResource;
    const res = Object.assign(Object.assign({}, rawRule), { resource: (resources) => {
            currentResource = resources;
            return true;
        }, resourceQuery: (query) => {
            if (!query) {
                return false;
            }
            const parsed = qs.parse(query.slice(1));
            if (parsed.vue == null) {
                return false;
            }
            if (!ruleCheck(parsed, compiledRule)) {
                return false;
            }
            const fakeResourcePath = ruleResource(parsed, currentResource);
            for (const condition of compiledRule.conditions) {
                // add support for resourceQuery
                const request = condition.property === 'resourceQuery' ? query : fakeResourcePath;
                if (condition && !condition.fn(request)) {
                    return false;
                }
            }
            return true;
        } });
    delete res.test;
    if (rawRule.rules) {
        res.rules = rawRule.rules.map((rule) => cloneRule(rule, refs, ruleCheck, ruleResource));
    }
    if (rawRule.oneOf) {
        res.oneOf = rawRule.oneOf.map((rule) => cloneRule(rule, refs, ruleCheck, ruleResource));
    }
    return res;
}
exports.default = VueLoaderPlugin;


code:
import type { LoaderContext } from 'webpack';
import type { SFCDescriptor, SFCScriptBlock } from 'vue/compiler-sfc';
import type { VueLoaderOptions } from 'src';
export declare const clientCache: WeakMap<SFCDescriptor, SFCScriptBlock | null>;
export declare const typeDepToSFCMap: Map<string, Set<string>>;
/**
 * inline template mode can only be enabled if:
 * - is production (separate compilation needed for HMR during dev)
 * - template has no pre-processor (separate loader chain required)
 * - template is not using src
 */
export declare function canInlineTemplate(descriptor: SFCDescriptor, isProd: boolean): boolean;
export declare function resolveScript(descriptor: SFCDescriptor, scopeId: string, options: VueLoaderOptions, loaderContext: LoaderContext<VueLoaderOptions>): SFCScriptBlock | null;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveScript = exports.canInlineTemplate = exports.typeDepToSFCMap = exports.clientCache = void 0;
const util_1 = require("./util");
const compiler_1 = require("./compiler");
const { compileScript } = compiler_1.compiler;
exports.clientCache = new WeakMap();
const serverCache = new WeakMap();
exports.typeDepToSFCMap = new Map();
/**
 * inline template mode can only be enabled if:
 * - is production (separate compilation needed for HMR during dev)
 * - template has no pre-processor (separate loader chain required)
 * - template is not using src
 */
function canInlineTemplate(descriptor, isProd) {
    const templateLang = descriptor.template && descriptor.template.lang;
    const templateSrc = descriptor.template && descriptor.template.src;
    return isProd && !!descriptor.scriptSetup && !templateLang && !templateSrc;
}
exports.canInlineTemplate = canInlineTemplate;
function resolveScript(descriptor, scopeId, options, loaderContext) {
    var _a;
    if (!descriptor.script && !descriptor.scriptSetup) {
        return null;
    }
    const isProd = loaderContext.mode === 'production' || process.env.NODE_ENV === 'production';
    const isServer = (_a = options.isServerBuild) !== null && _a !== void 0 ? _a : loaderContext.target === 'node';
    const enableInline = canInlineTemplate(descriptor, isProd);
    const cacheToUse = isServer ? serverCache : exports.clientCache;
    const cached = cacheToUse.get(descriptor);
    if (cached) {
        return cached;
    }
    let resolved = null;
    let templateCompiler;
    if (typeof options.compiler === 'string') {
        templateCompiler = require(options.compiler);
    }
    else {
        templateCompiler = options.compiler;
    }
    try {
        resolved = compileScript(descriptor, {
            id: scopeId,
            isProd,
            inlineTemplate: enableInline,
            // @ts-ignore this has been removed in 3.4
            reactivityTransform: options.reactivityTransform,
            propsDestructure: options.propsDestructure,
            defineModel: options.defineModel,
            babelParserPlugins: options.babelParserPlugins,
            templateOptions: {
                ssr: isServer,
                compiler: templateCompiler,
                compilerOptions: Object.assign(Object.assign({}, options.compilerOptions), (0, util_1.resolveTemplateTSOptions)(descriptor, options)),
                transformAssetUrls: options.transformAssetUrls || true,
            },
        });
    }
    catch (e) {
        loaderContext.emitError(e);
    }
    if (!isProd && (resolved === null || resolved === void 0 ? void 0 : resolved.deps)) {
        for (const [key, sfcs] of exports.typeDepToSFCMap) {
            if (sfcs.has(descriptor.filename) && !resolved.deps.includes(key)) {
                sfcs.delete(descriptor.filename);
                if (!sfcs.size) {
                    exports.typeDepToSFCMap.delete(key);
                }
            }
        }
        for (const dep of resolved.deps) {
            const existingSet = exports.typeDepToSFCMap.get(dep);
            if (!existingSet) {
                exports.typeDepToSFCMap.set(dep, new Set([descriptor.filename]));
            }
            else {
                existingSet.add(descriptor.filename);
            }
        }
    }
    cacheToUse.set(descriptor, resolved);
    return resolved;
}
exports.resolveScript = resolveScript;