code:
"use strict";
// vue compiler module for transforming `img:srcset` to a number of `require`s
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
exports.default = (transformAssetUrlsOptions) => ({
    postTransformNode: (node) => {
        transform(node, transformAssetUrlsOptions);
    }
});
// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
function transform(node, transformAssetUrlsOptions) {
    const tags = ['img', 'source'];
    if (tags.indexOf(node.tag) !== -1 && node.attrs) {
        node.attrs.forEach(attr => {
            if (attr.name === 'srcset') {
                // same logic as in transform-require.js
                const value = attr.value;
                const isStatic = value.charAt(0) === '"' && value.charAt(value.length - 1) === '"';
                if (!isStatic) {
                    return;
                }
                const imageCandidates = value
                    .substr(1, value.length - 2)
                    .split(',')
                    .map(s => {
                    // The attribute value arrives here with all whitespace, except
                    // normal spaces, represented by escape sequences
                    const [url, descriptor] = s
                        .replace(escapedSpaceCharacters, ' ')
                        .trim()
                        .split(' ', 2);
                    return {
                        require: utils_1.urlToRequire(url, transformAssetUrlsOptions),
                        descriptor
                    };
                });
                // "require(url1)"
                // "require(url1) 1x"
                // "require(url1), require(url2)"
                // "require(url1), require(url2) 2x"
                // "require(url1) 1x, require(url2)"
                // "require(url1) 1x, require(url2) 2x"
                const code = imageCandidates
                    .map(({ require, descriptor }) => `${require} + "${descriptor ? ' ' + descriptor : ''}, " + `)
                    .join('')
                    .slice(0, -6)
                    .concat('"')
                    .replace(/ \+ ""$/, '');
                attr.value = code;
            }
        });
    }
}


code:
import { TransformAssetUrlsOptions } from './assetUrl';
export interface Attr {
    name: string;
    value: string;
}
export interface ASTNode {
    tag: string;
    attrs: Attr[];
}
export declare function urlToRequire(url: string, transformAssetUrlsOption?: TransformAssetUrlsOptions): string;

license: mit


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.urlToRequire = void 0;
const url_1 = require("url");
const path_1 = __importDefault(require("path"));
function urlToRequire(url, transformAssetUrlsOption = {}) {
    const returnValue = `"${url}"`;
    // same logic as in transform-require.js
    const firstChar = url.charAt(0);
    if (firstChar === '~') {
        const secondChar = url.charAt(1);
        url = url.slice(secondChar === '/' ? 2 : 1);
    }
    const uriParts = parseUriParts(url);
    if (transformAssetUrlsOption.base) {
        // explicit base - directly rewrite the url into absolute url
        // does not apply to absolute urls or urls that start with `@`
        // since they are aliases
        if (firstChar === '.' || firstChar === '~') {
            // when packaged in the browser, path will be using the posix-
            // only version provided by rollup-plugin-node-builtins.
            return `"${(path_1.default.posix || path_1.default).join(transformAssetUrlsOption.base, uriParts.path + (uriParts.hash || ''))}"`;
        }
        return returnValue;
    }
    if (firstChar === '.' || firstChar === '~' || firstChar === '@') {
        if (!uriParts.hash) {
            return `require("${url}")`;
        }
        else {
            // support uri fragment case by excluding it from
            // the require and instead appending it as string;
            // assuming that the path part is sufficient according to
            // the above caseing(t.i. no protocol-auth-host parts expected)
            return `require("${uriParts.path}") + "${uriParts.hash}"`;
        }
    }
    return returnValue;
}
exports.urlToRequire = urlToRequire;
/**
 * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
 * @param urlString an url as a string
 */
function parseUriParts(urlString) {
    // initialize return value
    const returnValue = url_1.parse('');
    if (urlString) {
        // A TypeError is thrown if urlString is not a string
        // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
        if ('string' === typeof urlString) {
            // check is an uri
            return url_1.parse(urlString); // take apart the uri
        }
    }
    return returnValue;
}


code:
import { SFCDescriptor } from './parse';
export interface StartOfSourceMap {
    file?: string;
    sourceRoot?: string;
}
export interface RawSourceMap extends StartOfSourceMap {
    version: string;
    sources: string[];
    names: string[];
    sourcesContent?: string[];
    mappings: string;
}
export interface VueTemplateCompiler {
    parseComponent(source: string, options?: any): SFCDescriptor;
    compile(template: string, options: VueTemplateCompilerOptions): VueTemplateCompilerResults;
    ssrCompile(template: string, options: VueTemplateCompilerOptions): VueTemplateCompilerResults;
}
export interface VueTemplateCompilerOptions {
    modules?: Object[];
    outputSourceRange?: boolean;
    whitespace?: 'preserve' | 'condense';
    directives?: {
        [key: string]: Function;
    };
}
export interface VueTemplateCompilerParseOptions {
    pad?: 'line' | 'space';
}
export interface ErrorWithRange {
    msg: string;
    start: number;
    end: number;
}
export interface VueTemplateCompilerResults {
    ast: Object | undefined;
    render: string;
    staticRenderFns: string[];
    errors: (string | ErrorWithRange)[];
    tips: (string | ErrorWithRange)[];
}


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


code:
const postcss = require('postcss')
import { ProcessOptions, LazyResult } from 'postcss'
import trimPlugin from './stylePlugins/trim'
import scopedPlugin from './stylePlugins/scoped'
import {
  processors,
  StylePreprocessor,
  StylePreprocessorResults
} from './styleProcessors'

export interface StyleCompileOptions {
  source: string
  filename: string
  id: string
  map?: any
  scoped?: boolean
  trim?: boolean
  preprocessLang?: string
  preprocessOptions?: any
  postcssOptions?: any
  postcssPlugins?: any[]
}

export interface AsyncStyleCompileOptions extends StyleCompileOptions {
  isAsync?: boolean
}

export interface StyleCompileResults {
  code: string
  map: any | void
  rawResult: LazyResult | void
  errors: string[]
}

export function compileStyle(
  options: StyleCompileOptions
): StyleCompileResults {
  return doCompileStyle({ ...options, isAsync: false })
}

export function compileStyleAsync(
  options: StyleCompileOptions
): Promise<StyleCompileResults> {
  return Promise.resolve(doCompileStyle({ ...options, isAsync: true }))
}

export function doCompileStyle(
  options: AsyncStyleCompileOptions
): StyleCompileResults {
  const {
    filename,
    id,
    scoped = true,
    trim = true,
    preprocessLang,
    postcssOptions,
    postcssPlugins
  } = options
  const preprocessor = preprocessLang && processors[preprocessLang]
  const preProcessedSource = preprocessor && preprocess(options, preprocessor)
  const map = preProcessedSource ? preProcessedSource.map : options.map
  const source = preProcessedSource ? preProcessedSource.code : options.source

  const plugins = (postcssPlugins || []).slice()
  if (trim) {
    plugins.push(trimPlugin())
  }
  if (scoped) {
    plugins.push(scopedPlugin(id))
  }

  const postCSSOptions: ProcessOptions = {
    ...postcssOptions,
    to: filename,
    from: filename
  }
  if (map) {
    postCSSOptions.map = {
      inline: false,
      annotation: false,
      prev: map
    }
  }

  let result, code, outMap
  const errors: any[] = []
  if (preProcessedSource && preProcessedSource.errors.length) {
    errors.push(...preProcessedSource.errors)
  }
  try {
    result = postcss(plugins).process(source, postCSSOptions)

    // In async mode, return a promise.
    if (options.isAsync) {
      return result
        .then(
          (result: LazyResult): StyleCompileResults => ({
            code: result.css || '',
            map: result.map && result.map.toJSON(),
            errors,
            rawResult: result
          })
        )
        .catch(
          (error: Error): StyleCompileResults => ({
            code: '',
            map: undefined,
            errors: [...errors, error.message],
            rawResult: undefined
          })
        )
    }

    // force synchronous transform (we know we only have sync plugins)
    code = result.css
    outMap = result.map
  } catch (e) {
    errors.push(e)
  }

  return {
    code: code || ``,
    map: outMap && outMap.toJSON(),
    errors,
    rawResult: result
  }
}

function preprocess(
  options: StyleCompileOptions,
  preprocessor: StylePreprocessor
): StylePreprocessorResults {
  return preprocessor.render(
    options.source,
    options.map,
    Object.assign(
      {
        filename: options.filename
      },
      options.preprocessOptions
    )
  )
}


code:
import {
  VueTemplateCompiler,
  VueTemplateCompilerOptions,
  ErrorWithRange
} from './types'

import assetUrlsModule, {
  AssetURLOptions,
  TransformAssetUrlsOptions
} from './templateCompilerModules/assetUrl'
import srcsetModule from './templateCompilerModules/srcset'

const consolidate = require('consolidate')
const transpile = require('vue-template-es2015-compiler')

export interface TemplateCompileOptions {
  source: string
  filename: string
  compiler: VueTemplateCompiler
  compilerOptions?: VueTemplateCompilerOptions
  transformAssetUrls?: AssetURLOptions | boolean
  transformAssetUrlsOptions?: TransformAssetUrlsOptions
  preprocessLang?: string
  preprocessOptions?: any
  transpileOptions?: any
  isProduction?: boolean
  isFunctional?: boolean
  optimizeSSR?: boolean
  prettify?: boolean
}

export interface TemplateCompileResult {
  ast: Object | undefined
  code: string
  source: string
  tips: (string | ErrorWithRange)[]
  errors: (string | ErrorWithRange)[]
}

export function compileTemplate(
  options: TemplateCompileOptions
): TemplateCompileResult {
  const { preprocessLang } = options
  const preprocessor = preprocessLang && consolidate[preprocessLang]
  if (preprocessor) {
    return actuallyCompile(
      Object.assign({}, options, {
        source: preprocess(options, preprocessor)
      })
    )
  } else if (preprocessLang) {
    return {
      ast: {},
      code: `var render = function () {}\n` + `var staticRenderFns = []\n`,
      source: options.source,
      tips: [
        `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
      ],
      errors: [
        `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
      ]
    }
  } else {
    return actuallyCompile(options)
  }
}

function preprocess(
  options: TemplateCompileOptions,
  preprocessor: any
): string {
  const { source, filename, preprocessOptions } = options

  const finalPreprocessOptions = Object.assign(
    {
      filename
    },
    preprocessOptions
  )

  // Consolidate exposes a callback based API, but the callback is in fact
  // called synchronously for most templating engines. In our case, we have to
  // expose a synchronous API so that it is usable in Jest transforms (which
  // have to be sync because they are applied via Node.js require hooks)
  let res: any, err
  preprocessor.render(
    source,
    finalPreprocessOptions,
    (_err: Error | null, _res: string) => {
      if (_err) err = _err
      res = _res
    }
  )

  if (err) throw err
  return res
}

function actuallyCompile(
  options: TemplateCompileOptions
): TemplateCompileResult {
  const {
    source,
    compiler,
    compilerOptions = {},
    transpileOptions = {},
    transformAssetUrls,
    transformAssetUrlsOptions,
    isProduction = process.env.NODE_ENV === 'production',
    isFunctional = false,
    optimizeSSR = false,
    prettify = true
  } = options

  const compile =
    optimizeSSR && compiler.ssrCompile ? compiler.ssrCompile : compiler.compile

  let finalCompilerOptions = compilerOptions
  if (transformAssetUrls) {
    const builtInModules = [
      transformAssetUrls === true
        ? assetUrlsModule(undefined, transformAssetUrlsOptions)
        : assetUrlsModule(transformAssetUrls, transformAssetUrlsOptions),
      srcsetModule(transformAssetUrlsOptions)
    ]
    finalCompilerOptions = Object.assign({}, compilerOptions, {
      modules: [...builtInModules, ...(compilerOptions.modules || [])],
      filename: options.filename
    })
  }

  const { ast, render, staticRenderFns, tips, errors } = compile(
    source,
    finalCompilerOptions
  )

  if (errors && errors.length) {
    return {
      ast,
      code: `var render = function () {}\n` + `var staticRenderFns = []\n`,
      source,
      tips,
      errors
    }
  } else {
    const finalTranspileOptions = Object.assign({}, transpileOptions, {
      transforms: Object.assign({}, transpileOptions.transforms, {
        stripWithFunctional: isFunctional
      })
    })

    const toFunction = (code: string): string => {
      return `function (${isFunctional ? `_h,_vm` : ``}) {${code}}`
    }

    // transpile code with vue-template-es2015-compiler, which is a forked
    // version of Buble that applies ES2015 transforms + stripping `with` usage
    let code =
      transpile(
        `var __render__ = ${toFunction(render)}\n` +
          `var __staticRenderFns__ = [${staticRenderFns.map(toFunction)}]`,
        finalTranspileOptions
      ) + `\n`

    // #23 we use __render__ to avoid `render` not being prefixed by the
    // transpiler when stripping with, but revert it back to `render` to
    // maintain backwards compat
    code = code.replace(/\s__(render|staticRenderFns)__\s/g, ' $1 ')

    if (!isProduction) {
      // mark with stripped (this enables Vue to use correct runtime proxy
      // detection)
      code += `render._withStripped = true`

      if (prettify) {
        try {
          code = require('prettier').format(code, {
            semi: false,
            parser: 'babel'
          })
        } catch (e) {
          if (e.code === 'MODULE_NOT_FOUND') {
            tips.push(
              'The `prettify` option is on, but the dependency `prettier` is not found.\n' +
                'Please either turn off `prettify` or manually install `prettier`.'
            )
          }
          tips.push(
            `Failed to prettify component ${options.filename} template source after compilation.`
          )
        }
      }
    }

    return {
      ast,
      code,
      source,
      tips,
      errors
    }
  }
}


code:
import { parse, SFCBlock, SFCCustomBlock, SFCDescriptor } from './parse'

import {
  compileTemplate,
  TemplateCompileOptions,
  TemplateCompileResult
} from './compileTemplate'

import {
  compileStyle,
  compileStyleAsync,
  StyleCompileOptions,
  StyleCompileResults
} from './compileStyle'

// API
export { parse, compileTemplate, compileStyle, compileStyleAsync }

// types
export {
  SFCBlock,
  SFCCustomBlock,
  SFCDescriptor,
  TemplateCompileOptions,
  TemplateCompileResult,
  StyleCompileOptions,
  StyleCompileResults
}


code:
import { SourceMapGenerator } from 'source-map'
import {
  RawSourceMap,
  VueTemplateCompiler,
  VueTemplateCompilerParseOptions
} from './types'

const hash = require('hash-sum')
const cache = new (require('lru-cache'))(100)

const splitRE = /\r?\n/g
const emptyRE = /^(?:\/\/)?\s*$/

export interface ParseOptions {
  source: string
  filename?: string
  compiler: VueTemplateCompiler
  compilerParseOptions?: VueTemplateCompilerParseOptions
  sourceRoot?: string
  needMap?: boolean
}

export interface SFCCustomBlock {
  type: string
  content: string
  attrs: { [key: string]: string | true }
  start: number
  end: number
  map?: RawSourceMap
}

export interface SFCBlock extends SFCCustomBlock {
  lang?: string
  src?: string
  scoped?: boolean
  module?: string | boolean
}

export interface SFCDescriptor {
  template: SFCBlock | null
  script: SFCBlock | null
  styles: SFCBlock[]
  customBlocks: SFCCustomBlock[]
}

export function parse(options: ParseOptions): SFCDescriptor {
  const {
    source,
    filename = '',
    compiler,
    compilerParseOptions = { pad: 'line' } as VueTemplateCompilerParseOptions,
    sourceRoot = '',
    needMap = true
  } = options
  const cacheKey = hash(
    filename + source + JSON.stringify(compilerParseOptions)
  )
  let output: SFCDescriptor = cache.get(cacheKey)
  if (output) return output
  output = compiler.parseComponent(source, compilerParseOptions)
  if (needMap) {
    if (output.script && !output.script.src) {
      output.script.map = generateSourceMap(
        filename,
        source,
        output.script.content,
        sourceRoot,
        compilerParseOptions.pad
      )
    }
    if (output.styles) {
      output.styles.forEach(style => {
        if (!style.src) {
          style.map = generateSourceMap(
            filename,
            source,
            style.content,
            sourceRoot,
            compilerParseOptions.pad
          )
        }
      })
    }
  }
  cache.set(cacheKey, output)
  return output
}

function generateSourceMap(
  filename: string,
  source: string,
  generated: string,
  sourceRoot: string,
  pad?: 'line' | 'space'
): RawSourceMap {
  const map = new SourceMapGenerator({
    file: filename.replace(/\\/g, '/'),
    sourceRoot: sourceRoot.replace(/\\/g, '/')
  })
  let offset = 0
  if (!pad) {
    offset =
      source
        .split(generated)
        .shift()!
        .split(splitRE).length - 1
  }
  map.setSourceContent(filename, source)
  generated.split(splitRE).forEach((line, index) => {
    if (!emptyRE.test(line)) {
      map.addMapping({
        source: filename,
        original: {
          line: index + 1 + offset,
          column: 0
        },
        generated: {
          line: index + 1,
          column: 0
        }
      })
    }
  })
  return JSON.parse(map.toString())
}


code:
import { Root } from 'postcss'
import * as postcss from 'postcss'
// postcss-selector-parser does have typings but it's problematic to work with.
const selectorParser = require('postcss-selector-parser')

export default postcss.plugin('add-id', (options: any) => (root: Root) => {
  const id: string = options
  const keyframes = Object.create(null)

  root.each(function rewriteSelector(node: any) {
    if (!node.selector) {
      // handle media queries
      if (node.type === 'atrule') {
        if (node.name === 'media' || node.name === 'supports') {
          node.each(rewriteSelector)
        } else if (/-?keyframes$/.test(node.name)) {
          // register keyframes
          keyframes[node.params] = node.params = node.params + '-' + id
        }
      }
      return
    }
    node.selector = selectorParser((selectors: any) => {
      selectors.each((selector: any) => {
        let node: any = null

        // find the last child node to insert attribute selector
        selector.each((n: any) => {
          // ">>>" combinator
          // and /deep/ alias for >>>, since >>> doesn't work in SASS
          if (
            n.type === 'combinator' &&
            (n.value === '>>>' || n.value === '/deep/')
          ) {
            n.value = ' '
            n.spaces.before = n.spaces.after = ''
            return false
          }

          // in newer versions of sass, /deep/ support is also dropped, so add a ::v-deep alias
          if (n.type === 'pseudo' && n.value === '::v-deep') {
            n.value = n.spaces.before = n.spaces.after = ''
            return false
          }

          if (n.type !== 'pseudo' && n.type !== 'combinator') {
            node = n
          }
        })

        if (node) {
          node.spaces.after = ''
        } else {
          // For deep selectors & standalone pseudo selectors,
          // the attribute selectors are prepended rather than appended.
          // So all leading spaces must be eliminated to avoid problems.
          selector.first.spaces.before = ''
        }

        selector.insertAfter(
          node,
          selectorParser.attribute({
            attribute: id
          })
        )
      })
    }).processSync(node.selector)
  })

  // If keyframes are found in this <style>, find and rewrite animation names
  // in declarations.
  // Caveat: this only works for keyframes and animation rules in the same
  // <style> element.
  if (Object.keys(keyframes).length) {
    root.walkDecls(decl => {
      // individual animation-name declaration
      if (/^(-\w+-)?animation-name$/.test(decl.prop)) {
        decl.value = decl.value
          .split(',')
          .map(v => keyframes[v.trim()] || v.trim())
          .join(',')
      }
      // shorthand
      if (/^(-\w+-)?animation$/.test(decl.prop)) {
        decl.value = decl.value
          .split(',')
          .map(v => {
            const vals = v.trim().split(/\s+/)
            const i = vals.findIndex(val => keyframes[val])
            if (i !== -1) {
              vals.splice(i, 1, keyframes[vals[i]])
              return vals.join(' ')
            } else {
              return v
            }
          })
          .join(',')
      }
    })
  }
})


code:
import { Root } from 'postcss'
import * as postcss from 'postcss'

export default postcss.plugin('trim', () => (css: Root) => {
  css.walk(({ type, raws }) => {
    if (type === 'rule' || type === 'atrule') {
      if (raws.before) raws.before = '\n'
      if (raws.after) raws.after = '\n'
    }
  })
})


code:
const merge = require('merge-source-map')

export interface StylePreprocessor {
  render(
    source: string,
    map: any | null,
    options: any
  ): StylePreprocessorResults
}

export interface StylePreprocessorResults {
  code: string
  map?: any
  errors: Array<Error>
}

// .scss/.sass processor
const scss: StylePreprocessor = {
  render(
    source: string,
    map: any | null,
    options: any
  ): StylePreprocessorResults {
    const nodeSass = require('sass')
    const finalOptions = Object.assign({}, options, {
      data: source,
      file: options.filename,
      outFile: options.filename,
      sourceMap: !!map
    })

    try {
      const result = nodeSass.renderSync(finalOptions)

      if (map) {
        return {
          code: result.css.toString(),
          map: merge(map, JSON.parse(result.map.toString())),
          errors: []
        }
      }

      return { code: result.css.toString(), errors: [] }
    } catch (e) {
      return { code: '', errors: [e] }
    }
  }
}

const sass = {
  render(
    source: string,
    map: any | null,
    options: any
  ): StylePreprocessorResults {
    return scss.render(
      source,
      map,
      Object.assign({}, options, { indentedSyntax: true })
    )
  }
}

// .less
const less = {
  render(
    source: string,
    map: any | null,
    options: any
  ): StylePreprocessorResults {
    const nodeLess = require('less')

    let result: any
    let error: Error | null = null
    nodeLess.render(
      source,
      Object.assign({}, options, { syncImport: true }),
      (err: Error | null, output: any) => {
        error = err
        result = output
      }
    )

    if (error) return { code: '', errors: [error] }

    if (map) {
      return {
        code: result.css.toString(),
        map: merge(map, result.map),
        errors: []
      }
    }

    return { code: result.css.toString(), errors: [] }
  }
}

// .styl
const styl = {
  render(
    source: string,
    map: any | null,
    options: any
  ): StylePreprocessorResults {
    const nodeStylus = require('stylus')
    try {
      const ref = nodeStylus(source)
      Object.keys(options).forEach(key => ref.set(key, options[key]))
      if (map) ref.set('sourcemap', { inline: false, comment: false })

      const result = ref.render()
      if (map) {
        return {
          code: result,
          map: merge(map, ref.sourcemap),
          errors: []
        }
      }

      return { code: result, errors: [] }
    } catch (e) {
      return { code: '', errors: [e] }
    }
  }
}

export const processors: { [key: string]: StylePreprocessor } = {
  less,
  sass,
  scss,
  styl,
  stylus: styl
}


code:
// vue compiler module for transforming `<tag>:<attribute>` to `require`

import { urlToRequire, ASTNode, Attr } from './utils'

export interface AssetURLOptions {
  [name: string]: string | string[]
}

export interface TransformAssetUrlsOptions {
  /**
   * If base is provided, instead of transforming relative asset urls into
   * imports, they will be directly rewritten to absolute urls.
   */
  base?: string
}

const defaultOptions: AssetURLOptions = {
  audio: 'src',
  video: ['src', 'poster'],
  source: 'src',
  img: 'src',
  image: ['xlink:href', 'href'],
  use: ['xlink:href', 'href']
}

export default (
  userOptions?: AssetURLOptions,
  transformAssetUrlsOption?: TransformAssetUrlsOptions
) => {
  const options = userOptions
    ? Object.assign({}, defaultOptions, userOptions)
    : defaultOptions

  return {
    postTransformNode: (node: ASTNode) => {
      transform(node, options, transformAssetUrlsOption)
    }
  }
}

function transform(
  node: ASTNode,
  options: AssetURLOptions,
  transformAssetUrlsOption?: TransformAssetUrlsOptions
) {
  for (const tag in options) {
    if ((tag === '*' || node.tag === tag) && node.attrs) {
      const attributes = options[tag]
      if (typeof attributes === 'string') {
        node.attrs.some(attr =>
          rewrite(attr, attributes, transformAssetUrlsOption)
        )
      } else if (Array.isArray(attributes)) {
        attributes.forEach(item =>
          node.attrs.some(attr => rewrite(attr, item, transformAssetUrlsOption))
        )
      }
    }
  }
}

function rewrite(
  attr: Attr,
  name: string,
  transformAssetUrlsOption?: TransformAssetUrlsOptions
) {
  if (attr.name === name) {
    const value = attr.value
    // only transform static URLs
    if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
      attr.value = urlToRequire(value.slice(1, -1), transformAssetUrlsOption)
      return true
    }
  }
  return false
}


code:
// vue compiler module for transforming `img:srcset` to a number of `require`s

import { urlToRequire, ASTNode } from './utils'
import { TransformAssetUrlsOptions } from './assetUrl'

interface ImageCandidate {
  require: string
  descriptor: string
}

export default (transformAssetUrlsOptions?: TransformAssetUrlsOptions) => ({
  postTransformNode: (node: ASTNode) => {
    transform(node, transformAssetUrlsOptions)
  }
})

// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g

function transform(
  node: ASTNode,
  transformAssetUrlsOptions?: TransformAssetUrlsOptions
) {
  const tags = ['img', 'source']

  if (tags.indexOf(node.tag) !== -1 && node.attrs) {
    node.attrs.forEach(attr => {
      if (attr.name === 'srcset') {
        // same logic as in transform-require.js
        const value = attr.value
        const isStatic =
          value.charAt(0) === '"' && value.charAt(value.length - 1) === '"'
        if (!isStatic) {
          return
        }

        const imageCandidates: ImageCandidate[] = value
          .substr(1, value.length - 2)
          .split(',')
          .map(s => {
            // The attribute value arrives here with all whitespace, except
            // normal spaces, represented by escape sequences
            const [url, descriptor] = s
              .replace(escapedSpaceCharacters, ' ')
              .trim()
              .split(' ', 2)
            return {
              require: urlToRequire(url, transformAssetUrlsOptions),
              descriptor
            }
          })

        // "require(url1)"
        // "require(url1) 1x"
        // "require(url1), require(url2)"
        // "require(url1), require(url2) 2x"
        // "require(url1) 1x, require(url2)"
        // "require(url1) 1x, require(url2) 2x"
        const code = imageCandidates
          .map(
            ({ require, descriptor }) =>
              `${require} + "${descriptor ? ' ' + descriptor : ''}, " + `
          )
          .join('')
          .slice(0, -6)
          .concat('"')
          .replace(/ \+ ""$/, '')

        attr.value = code
      }
    })
  }
}


code:
import { TransformAssetUrlsOptions } from './assetUrl'
import { UrlWithStringQuery, parse as uriParse } from 'url'
import path from 'path'

export interface Attr {
  name: string
  value: string
}

export interface ASTNode {
  tag: string
  attrs: Attr[]
}

export function urlToRequire(
  url: string,
  transformAssetUrlsOption: TransformAssetUrlsOptions = {}
): string {
  const returnValue = `"${url}"`
  // same logic as in transform-require.js
  const firstChar = url.charAt(0)
  if (firstChar === '~') {
    const secondChar = url.charAt(1)
    url = url.slice(secondChar === '/' ? 2 : 1)
  }

  const uriParts = parseUriParts(url)

  if (transformAssetUrlsOption.base) {
    // explicit base - directly rewrite the url into absolute url
    // does not apply to absolute urls or urls that start with `@`
    // since they are aliases
    if (firstChar === '.' || firstChar === '~') {
      // when packaged in the browser, path will be using the posix-
      // only version provided by rollup-plugin-node-builtins.
      return `"${(path.posix || path).join(
        transformAssetUrlsOption.base,
        uriParts.path + (uriParts.hash || '')
      )}"`
    }
    return returnValue
  }

  if (firstChar === '.' || firstChar === '~' || firstChar === '@') {
    if (!uriParts.hash) {
      return `require("${url}")`
    } else {
      // support uri fragment case by excluding it from
      // the require and instead appending it as string;
      // assuming that the path part is sufficient according to
      // the above caseing(t.i. no protocol-auth-host parts expected)
      return `require("${uriParts.path}") + "${uriParts.hash}"`
    }
  }
  return returnValue
}

/**
 * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
 * @param urlString an url as a string
 */
function parseUriParts(urlString: string): UrlWithStringQuery {
  // initialize return value
  const returnValue: UrlWithStringQuery = uriParse('')
  if (urlString) {
    // A TypeError is thrown if urlString is not a string
    // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
    if ('string' === typeof urlString) {
      // check is an uri
      return uriParse(urlString) // take apart the uri
    }
  }
  return returnValue
}


code:
import { SFCDescriptor } from './parse'

export interface StartOfSourceMap {
  file?: string
  sourceRoot?: string
}

export interface RawSourceMap extends StartOfSourceMap {
  version: string
  sources: string[]
  names: string[]
  sourcesContent?: string[]
  mappings: string
}

export interface VueTemplateCompiler {
  parseComponent(source: string, options?: any): SFCDescriptor

  compile(
    template: string,
    options: VueTemplateCompilerOptions
  ): VueTemplateCompilerResults

  ssrCompile(
    template: string,
    options: VueTemplateCompilerOptions
  ): VueTemplateCompilerResults
}

// we'll just shim this much for now - in the future these types
// should come from vue-template-compiler directly, or this package should be
// part of the vue monorepo.
export interface VueTemplateCompilerOptions {
  modules?: Object[]
  outputSourceRange?: boolean
  whitespace?: 'preserve' | 'condense'
  directives?: { [key: string]: Function }
}

export interface VueTemplateCompilerParseOptions {
  pad?: 'line' | 'space'
}

export interface ErrorWithRange {
  msg: string
  start: number
  end: number
}

export interface VueTemplateCompilerResults {
  ast: Object | undefined
  render: string
  staticRenderFns: string[]
  errors: (string | ErrorWithRange)[]
  tips: (string | ErrorWithRange)[]
}


code:
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

case `uname` in
    *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac

if [ -x "$basedir/node" ]; then
  exec "$basedir/node"  "$basedir/../prettier/bin-prettier.js" "$@"
else
  exec node  "$basedir/../prettier/bin-prettier.js" "$@"
fi


code:
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0

IF EXIST "%dp0%\node.exe" (
  SET "_prog=%dp0%\node.exe"
) ELSE (
  SET "_prog=node"
  SET PATHEXT=%PATHEXT:;.JS;=;%
)

endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%"  "%dp0%\..\prettier\bin-prettier.js" %*


code:
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent

$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
  # Fix case when both the Windows and Linux builds of Node
  # are installed in the same directory
  $exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
  # Support pipeline input
  if ($MyInvocation.ExpectingInput) {
    $input | & "$basedir/node$exe"  "$basedir/../prettier/bin-prettier.js" $args
  } else {
    & "$basedir/node$exe"  "$basedir/../prettier/bin-prettier.js" $args
  }
  $ret=$LASTEXITCODE
} else {
  # Support pipeline input
  if ($MyInvocation.ExpectingInput) {
    $input | & "node$exe"  "$basedir/../prettier/bin-prettier.js" $args
  } else {
    & "node$exe"  "$basedir/../prettier/bin-prettier.js" $args
  }
  $ret=$LASTEXITCODE
}
exit $ret


code:
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false


code:
# 1.0.2 Quick Sort

- Sorts object keys so that property order doesn't affect outcome

# 1.0.1 Perfect Circle

- Guard against circular references

# 1.0.0 IPO

- Initial Public Release


code:
'use strict';

function pad (hash, len) {
  while (hash.length < len) {
    hash = '0' + hash;
  }
  return hash;
}

function fold (hash, text) {
  var i;
  var chr;
  var len;
  if (text.length === 0) {
    return hash;
  }
  for (i = 0, len = text.length; i < len; i++) {
    chr = text.charCodeAt(i);
    hash = ((hash << 5) - hash) + chr;
    hash |= 0;
  }
  return hash < 0 ? hash * -2 : hash;
}

function foldObject (hash, o, seen) {
  return Object.keys(o).sort().reduce(foldKey, hash);
  function foldKey (hash, key) {
    return foldValue(hash, o[key], key, seen);
  }
}

function foldValue (input, value, key, seen) {
  var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  if (value === null) {
    return fold(hash, 'null');
  }
  if (value === undefined) {
    return fold(hash, 'undefined');
  }
  if (typeof value === 'object') {
    if (seen.indexOf(value) !== -1) {
      return fold(hash, '[Circular]' + key);
    }
    seen.push(value);
    return foldObject(hash, value, seen);
  }
  return fold(hash, value.toString());
}

function toString (o) {
  return Object.prototype.toString.call(o);
}

function sum (o) {
  return pad(foldValue(0, o, '', []).toString(16), 8);
}

module.exports = sum;


hash-sum

description: Blazing fast unique hash generator

license: MIT

type: git

test: jshint . && tape test.js


code:
# hash-sum

> blazing fast unique hash generator

# install

```shell
npm i hash-sum -S
```

# features

- no dependencies
- minimal footprint
- works in all of node.js, io.js, and the browser
- hashes functions based on their source code
- produces different hashes for different object types
- support for circular references in objects
- ignores property assignment order

# `sum(value)`

yields a four-byte hexadecimal hash based off of `value`.

```
# creates unique hashes
 creates unique hashes
4d237d49 from: [ 0, 1, 2, 3 ]
766ec173 from: { url: 12 }
2f473108 from: { headers: 12 }
23308836 from: { headers: 122 }
062bce44 from: { headers: '122' }
acb9f66e from: { headers: { accept: 'text/plain' } }
1c365a2d from: { payload: [ 0, 1, 2, 3 ], headers: [ { a: 'b' } ] }
7319ae9d from: { a: [Function] }
8a3a0e86 from: { b: [Function] }
b6d7f5d4 from: { b: [Function] }
6c95fc65 from: function () {}
2941766e from: function (a) {}
294f8def from: function (b) {}
2d9c0cb8 from: function (a) { return a;}
ed5c63fc from: function (a) {return a;}
bba68bf6 from: ''
2d27667d from: 'null'
774b96ed from: 'false'
2d2a1684 from: 'true'
8daa1a0c from: '0'
8daa1a0a from: '1'
e38f07cc from: 'void 0'
6037ea1a from: 'undefined'
9b7df12e from: null
3c206f76 from: false
01e34ba8 from: true
1a96284a from: 0
1a96284b from: 1
29172c1a from: undefined
4505230f from: {}
3718c6e8 from: { a: {}, b: {} }
5d844489 from: []
938eaaf0 from: Tue Jul 14 2015 15:35:36 GMT-0300 (ART)
dfe5fb2e from: global
ok 1 should be equal
```

# license

MIT


code:
'use strict';

var _ = require('lodash');
var test = require('tape');
var sum = require('./');

test('creates unique hashes', function (t) {
  var results = [];
  sub([0,1,2,3]);
  sub({url:12});
  sub({headers:12});
  sub({headers:122});
  sub({headers:'122'});
  sub({headers:{accept:'text/plain'}});
  sub({payload:[0,1,2,3],headers:[{a:'b'}]});
  sub({a:function () {}});
  sub({b:function () {}});
  sub({b:function (a) {}});
  sub(function () {});
  sub(function (a) {});
  sub(function (b) {});
  sub(function (a) { return a;});
  sub(function (a) {return a;});
  sub('');
  sub('null');
  sub('false');
  sub('true');
  sub('0');
  sub('1');
  sub('void 0');
  sub('undefined');
  sub(null);
  sub(false);
  sub(true);
  sub(0);
  sub(1);
  sub(void 0);
  sub({});
  sub({a:{},b:{}});
  sub([]);
  sub(new Date());
  sub(global, 'global');
  t.equal(results.length, _.uniq(results).length);
  t.end();

  function sub (value, name) {
    var hash = sum(value);
    results.push(hash);
    console.log('%s from:', hash, name || value);
  }
});

test('hashes clash if same properties', function (t) {
  equals({a:'1'},{a:'1'});
  equals({a:'1',b:1},{b:1,a:'1'});
  t.end();

  function equals (a, b) {
    t.equal(sum(a), sum(b));
  }
});


code:
# lru cache

A cache object that deletes the least-recently-used items.

[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache)

## Installation:

```javascript
npm install lru-cache --save
```

## Usage:

```javascript
var LRU = require("lru-cache")
  , options = { max: 500
              , length: function (n, key) { return n * 2 + key.length }
              , dispose: function (key, n) { n.close() }
              , maxAge: 1000 * 60 * 60 }
  , cache = LRU(options)
  , otherCache = LRU(50) // sets just the max size

cache.set("key", "value")
cache.get("key") // "value"

// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)

cache.reset()    // empty the cache
```

If you put more stuff in it, then items will fall out.

If you try to put an oversized thing in it, then it'll fall out right
away.

## Options

* `max` The maximum size of the cache, checked by applying the length
  function to all values in the cache.  Not setting this is kind of
  silly, since that's the whole purpose of this lib, but it defaults
  to `Infinity`.
* `maxAge` Maximum age in ms.  Items are not pro-actively pruned out
  as they age, but if you try to get an item that is too old, it'll
  drop it and return undefined instead of giving it to you.
* `length` Function that is used to calculate the length of stored
  items.  If you're storing strings or buffers, then you probably want
  to do something like `function(n, key){return n.length}`.  The default is
  `function(){return 1}`, which is fine if you want to store `max`
  like-sized things.  The item is passed as the first argument, and
  the key is passed as the second argumnet.
* `dispose` Function that is called on items when they are dropped
  from the cache.  This can be handy if you want to close file
  descriptors or do other cleanup tasks when items are no longer
  accessible.  Called with `key, value`.  It's called *before*
  actually removing the item from the internal cache, so if you want
  to immediately put it back in, you'll have to do that in a
  `nextTick` or `setTimeout` callback or it won't do anything.
* `stale` By default, if you set a `maxAge`, it'll only actually pull
  stale items out of the cache when you `get(key)`.  (That is, it's
  not pre-emptively doing a `setTimeout` or anything.)  If you set
  `stale:true`, it'll return the stale value before deleting it.  If
  you don't set this, then it'll return `undefined` when you try to
  get a stale entry, as if it had already been deleted.
* `noDisposeOnSet` By default, if you set a `dispose()` method, then
  it'll be called whenever a `set()` operation overwrites an existing
  key.  If you set this option, `dispose()` will only be called when a
  key falls out of the cache, not when it is overwritten.

## API

* `set(key, value, maxAge)`
* `get(key) => value`

    Both of these will update the "recently used"-ness of the key.
    They do what you think. `maxAge` is optional and overrides the
    cache `maxAge` option if provided.

    If the key is not found, `get()` will return `undefined`.

    The key and val can be any value.

* `peek(key)`

    Returns the key value (or `undefined` if not found) without
    updating the "recently used"-ness of the key.

    (If you find yourself using this a lot, you *might* be using the
    wrong sort of data structure, but there are some use cases where
    it's handy.)

* `del(key)`

    Deletes a key out of the cache.

* `reset()`

    Clear the cache entirely, throwing away all values.

* `has(key)`

    Check if a key is in the cache, without updating the recent-ness
    or deleting it for being stale.

* `forEach(function(value,key,cache), [thisp])`

    Just like `Array.prototype.forEach`.  Iterates over all the keys
    in the cache, in order of recent-ness.  (Ie, more recently used
    items are iterated over first.)

* `rforEach(function(value,key,cache), [thisp])`

    The same as `cache.forEach(...)` but items are iterated over in
    reverse order.  (ie, less recently used items are iterated over
    first.)

* `keys()`

    Return an array of the keys in the cache.

* `values()`

    Return an array of the values in the cache.

* `length`

    Return total length of objects in cache taking into account
    `length` options function.

* `itemCount`

    Return total quantity of objects currently in cache. Note, that
    `stale` (see options) items are returned as part of this item
    count.

* `dump()`

    Return an array of the cache entries ready for serialization and usage
    with 'destinationCache.load(arr)`.

* `load(cacheEntriesArray)`

    Loads another cache entries array, obtained with `sourceCache.dump()`,
    into the cache. The destination cache is reset before loading new entries

* `prune()`

    Manually iterates over the entire cache proactively pruning old entries


code:
'use strict'

module.exports = LRUCache

// This will be a proper iterable 'Map' in engines that support it,
// or a fakey-fake PseudoMap in older versions.
var Map = require('pseudomap')
var util = require('util')

// A linked list to keep track of recently-used-ness
var Yallist = require('yallist')

// use symbols if possible, otherwise just _props
var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1'
var makeSymbol
if (hasSymbol) {
  makeSymbol = function (key) {
    return Symbol(key)
  }
} else {
  makeSymbol = function (key) {
    return '_' + key
  }
}

var MAX = makeSymbol('max')
var LENGTH = makeSymbol('length')
var LENGTH_CALCULATOR = makeSymbol('lengthCalculator')
var ALLOW_STALE = makeSymbol('allowStale')
var MAX_AGE = makeSymbol('maxAge')
var DISPOSE = makeSymbol('dispose')
var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet')
var LRU_LIST = makeSymbol('lruList')
var CACHE = makeSymbol('cache')

function naiveLength () { return 1 }

// lruList is a yallist where the head is the youngest
// item, and the tail is the oldest.  the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node.  This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
function LRUCache (options) {
  if (!(this instanceof LRUCache)) {
    return new LRUCache(options)
  }

  if (typeof options === 'number') {
    options = { max: options }
  }

  if (!options) {
    options = {}
  }

  var max = this[MAX] = options.max
  // Kind of weird to have a default max of Infinity, but oh well.
  if (!max ||
      !(typeof max === 'number') ||
      max <= 0) {
    this[MAX] = Infinity
  }

  var lc = options.length || naiveLength
  if (typeof lc !== 'function') {
    lc = naiveLength
  }
  this[LENGTH_CALCULATOR] = lc

  this[ALLOW_STALE] = options.stale || false
  this[MAX_AGE] = options.maxAge || 0
  this[DISPOSE] = options.dispose
  this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
  this.reset()
}

// resize the cache when the max changes.
Object.defineProperty(LRUCache.prototype, 'max', {
  set: function (mL) {
    if (!mL || !(typeof mL === 'number') || mL <= 0) {
      mL = Infinity
    }
    this[MAX] = mL
    trim(this)
  },
  get: function () {
    return this[MAX]
  },
  enumerable: true
})

Object.defineProperty(LRUCache.prototype, 'allowStale', {
  set: function (allowStale) {
    this[ALLOW_STALE] = !!allowStale
  },
  get: function () {
    return this[ALLOW_STALE]
  },
  enumerable: true
})

Object.defineProperty(LRUCache.prototype, 'maxAge', {
  set: function (mA) {
    if (!mA || !(typeof mA === 'number') || mA < 0) {
      mA = 0
    }
    this[MAX_AGE] = mA
    trim(this)
  },
  get: function () {
    return this[MAX_AGE]
  },
  enumerable: true
})

// resize the cache when the lengthCalculator changes.
Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
  set: function (lC) {
    if (typeof lC !== 'function') {
      lC = naiveLength
    }
    if (lC !== this[LENGTH_CALCULATOR]) {
      this[LENGTH_CALCULATOR] = lC
      this[LENGTH] = 0
      this[LRU_LIST].forEach(function (hit) {
        hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
        this[LENGTH] += hit.length
      }, this)
    }
    trim(this)
  },
  get: function () { return this[LENGTH_CALCULATOR] },
  enumerable: true
})

Object.defineProperty(LRUCache.prototype, 'length', {
  get: function () { return this[LENGTH] },
  enumerable: true
})

Object.defineProperty(LRUCache.prototype, 'itemCount', {
  get: function () { return this[LRU_LIST].length },
  enumerable: true
})

LRUCache.prototype.rforEach = function (fn, thisp) {
  thisp = thisp || this
  for (var walker = this[LRU_LIST].tail; walker !== null;) {
    var prev = walker.prev
    forEachStep(this, fn, walker, thisp)
    walker = prev
  }
}

function forEachStep (self, fn, node, thisp) {
  var hit = node.value
  if (isStale(self, hit)) {
    del(self, node)
    if (!self[ALLOW_STALE]) {
      hit = undefined
    }
  }
  if (hit) {
    fn.call(thisp, hit.value, hit.key, self)
  }
}

LRUCache.prototype.forEach = function (fn, thisp) {
  thisp = thisp || this
  for (var walker = this[LRU_LIST].head; walker !== null;) {
    var next = walker.next
    forEachStep(this, fn, walker, thisp)
    walker = next
  }
}

LRUCache.prototype.keys = function () {
  return this[LRU_LIST].toArray().map(function (k) {
    return k.key
  }, this)
}

LRUCache.prototype.values = function () {
  return this[LRU_LIST].toArray().map(function (k) {
    return k.value
  }, this)
}

LRUCache.prototype.reset = function () {
  if (this[DISPOSE] &&
      this[LRU_LIST] &&
      this[LRU_LIST].length) {
    this[LRU_LIST].forEach(function (hit) {
      this[DISPOSE](hit.key, hit.value)
    }, this)
  }

  this[CACHE] = new Map() // hash of items by key
  this[LRU_LIST] = new Yallist() // list of items in order of use recency
  this[LENGTH] = 0 // length of items in the list
}

LRUCache.prototype.dump = function () {
  return this[LRU_LIST].map(function (hit) {
    if (!isStale(this, hit)) {
      return {
        k: hit.key,
        v: hit.value,
        e: hit.now + (hit.maxAge || 0)
      }
    }
  }, this).toArray().filter(function (h) {
    return h
  })
}

LRUCache.prototype.dumpLru = function () {
  return this[LRU_LIST]
}

/* istanbul ignore next */
LRUCache.prototype.inspect = function (n, opts) {
  var str = 'LRUCache {'
  var extras = false

  var as = this[ALLOW_STALE]
  if (as) {
    str += '\n  allowStale: true'
    extras = true
  }

  var max = this[MAX]
  if (max && max !== Infinity) {
    if (extras) {
      str += ','
    }
    str += '\n  max: ' + util.inspect(max, opts)
    extras = true
  }

  var maxAge = this[MAX_AGE]
  if (maxAge) {
    if (extras) {
      str += ','
    }
    str += '\n  maxAge: ' + util.inspect(maxAge, opts)
    extras = true
  }

  var lc = this[LENGTH_CALCULATOR]
  if (lc && lc !== naiveLength) {
    if (extras) {
      str += ','
    }
    str += '\n  length: ' + util.inspect(this[LENGTH], opts)
    extras = true
  }

  var didFirst = false
  this[LRU_LIST].forEach(function (item) {
    if (didFirst) {
      str += ',\n  '
    } else {
      if (extras) {
        str += ',\n'
      }
      didFirst = true
      str += '\n  '
    }
    var key = util.inspect(item.key).split('\n').join('\n  ')
    var val = { value: item.value }
    if (item.maxAge !== maxAge) {
      val.maxAge = item.maxAge
    }
    if (lc !== naiveLength) {
      val.length = item.length
    }
    if (isStale(this, item)) {
      val.stale = true
    }

    val = util.inspect(val, opts).split('\n').join('\n  ')
    str += key + ' => ' + val
  })

  if (didFirst || extras) {
    str += '\n'
  }
  str += '}'

  return str
}

LRUCache.prototype.set = function (key, value, maxAge) {
  maxAge = maxAge || this[MAX_AGE]

  var now = maxAge ? Date.now() : 0
  var len = this[LENGTH_CALCULATOR](value, key)

  if (this[CACHE].has(key)) {
    if (len > this[MAX]) {
      del(this, this[CACHE].get(key))
      return false
    }

    var node = this[CACHE].get(key)
    var item = node.value

    // dispose of the old one before overwriting
    // split out into 2 ifs for better coverage tracking
    if (this[DISPOSE]) {
      if (!this[NO_DISPOSE_ON_SET]) {
        this[DISPOSE](key, item.value)
      }
    }

    item.now = now
    item.maxAge = maxAge
    item.value = value
    this[LENGTH] += len - item.length
    item.length = len
    this.get(key)
    trim(this)
    return true
  }

  var hit = new Entry(key, value, len, now, maxAge)

  // oversized objects fall out of cache automatically.
  if (hit.length > this[MAX]) {
    if (this[DISPOSE]) {
      this[DISPOSE](key, value)
    }
    return false
  }

  this[LENGTH] += hit.length
  this[LRU_LIST].unshift(hit)
  this[CACHE].set(key, this[LRU_LIST].head)
  trim(this)
  return true
}

LRUCache.prototype.has = function (key) {
  if (!this[CACHE].has(key)) return false
  var hit = this[CACHE].get(key).value
  if (isStale(this, hit)) {
    return false
  }
  return true
}

LRUCache.prototype.get = function (key) {
  return get(this, key, true)
}

LRUCache.prototype.peek = function (key) {
  return get(this, key, false)
}

LRUCache.prototype.pop = function () {
  var node = this[LRU_LIST].tail
  if (!node) return null
  del(this, node)
  return node.value
}

LRUCache.prototype.del = function (key) {
  del(this, this[CACHE].get(key))
}

LRUCache.prototype.load = function (arr) {
  // reset the cache
  this.reset()

  var now = Date.now()
  // A previous serialized cache has the most recent items first
  for (var l = arr.length - 1; l >= 0; l--) {
    var hit = arr[l]
    var expiresAt = hit.e || 0
    if (expiresAt === 0) {
      // the item was created without expiration in a non aged cache
      this.set(hit.k, hit.v)
    } else {
      var maxAge = expiresAt - now
      // dont add already expired items
      if (maxAge > 0) {
        this.set(hit.k, hit.v, maxAge)
      }
    }
  }
}

LRUCache.prototype.prune = function () {
  var self = this
  this[CACHE].forEach(function (value, key) {
    get(self, key, false)
  })
}

function get (self, key, doUse) {
  var node = self[CACHE].get(key)
  if (node) {
    var hit = node.value
    if (isStale(self, hit)) {
      del(self, node)
      if (!self[ALLOW_STALE]) hit = undefined
    } else {
      if (doUse) {
        self[LRU_LIST].unshiftNode(node)
      }
    }
    if (hit) hit = hit.value
  }
  return hit
}

function isStale (self, hit) {
  if (!hit || (!hit.maxAge && !self[MAX_AGE])) {
    return false
  }
  var stale = false
  var diff = Date.now() - hit.now
  if (hit.maxAge) {
    stale = diff > hit.maxAge
  } else {
    stale = self[MAX_AGE] && (diff > self[MAX_AGE])
  }
  return stale
}

function trim (self) {
  if (self[LENGTH] > self[MAX]) {
    for (var walker = self[LRU_LIST].tail;
      self[LENGTH] > self[MAX] && walker !== null;) {
      // We know that we're about to delete this one, and also
      // what the next least recently used key will be, so just
      // go ahead and set it now.
      var prev = walker.prev
      del(self, walker)
      walker = prev
    }
  }
}

function del (self, node) {
  if (node) {
    var hit = node.value
    if (self[DISPOSE]) {
      self[DISPOSE](hit.key, hit.value)
    }
    self[LENGTH] -= hit.length
    self[CACHE].delete(hit.key)
    self[LRU_LIST].removeNode(node)
  }
}

// classy, since V8 prefers predictable objects.
function Entry (key, value, length, now, maxAge) {
  this.key = key
  this.value = value
  this.length = length
  this.now = now
  this.maxAge = maxAge || 0
}


lru-cache

description: A cache object that deletes the least-recently-used items.

author: Isaac Z. Schlueter <i@izs.me>

keywords: mru lru cache

test: tap test/*.js --100 -J

snap: TAP_SNAPSHOT=1 tap test/*.js -J

posttest: standard test/*.js index.js

coveragerport: tap --coverage-report=html

lintfix: standard --fix test/*.js index.js

preversion: npm test

postversion: npm publish --tag=legacy

postpublish: git push origin --all; git push origin --tags

license: ISC


code:
# picocolors

    npm install picocolors

A tinier and faster alternative to [nanocolors](https://github.com/ai/nanocolors). Andrey, are you even trying?

```javascript
import pc from "picocolors";

console.log(pc.green(`How are ${pc.italic(`you`)} doing?`));
```

- Up to [2x faster and 2x smaller](#benchmarks) than alternatives
- 3x faster and 10x smaller than `chalk`
- [TypeScript](https://www.typescriptlang.org/) support
- [`NO_COLOR`](https://no-color.org/) friendly
- Node.js v6+ & browsers support
- The same API, but faster, much faster
- No `String.prototype` modifications (anyone still doing it?)
- No dependencies and the smallest `node_modules` footprint

## Docs
Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub.


picocolors

description: The tiniest and the fastest coloring library ever

keywords: terminal colors formatting cli console

author: Alexey Raspopov

repository: alexeyraspopov/picocolors


code:
var x=String;
var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x}};
module.exports=create();
module.exports.createColors = create;


code:
import { Colors } from "./types"

declare const picocolors: Colors & { createColors: (enabled: boolean) => Colors }

export = picocolors


code:
let tty = require("tty")

let isColorSupported =
	!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
	("FORCE_COLOR" in process.env ||
		process.argv.includes("--color") ||
		process.platform === "win32" ||
		(tty.isatty(1) && process.env.TERM !== "dumb") ||
		"CI" in process.env)

function formatter(open, close, replace = open) {
	return (input) => {
		let string = "" + input
		let index = string.indexOf(close, open.length)
		return !~index
			? open + string + close
			: open + replaceClose(string, close, replace, index) + close
	}
}

function replaceClose(string, close, replace, index) {
	let start = string.substring(0, index) + replace
	let end = string.substring(index + close.length)
	let nextIndex = end.indexOf(close)
	return !~nextIndex ? start + end : start + replaceClose(end, close, replace, nextIndex)
}

function createColors(enabled = isColorSupported) {
	return {
		isColorSupported: enabled,
		reset: enabled ? (s) => `\x1b[0m${s}\x1b[0m` : String,
		bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
		dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
		italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
		underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
		inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
		hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
		strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
		black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
		red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
		green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
		yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
		blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
		magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
		cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
		white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
		gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
		bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
		bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
		bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
		bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
		bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
		bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
		bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
		bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
	}
}

module.exports = createColors()
module.exports.createColors = createColors


code:
export type Formatter = (input: string | number | null | undefined) => string

export interface Colors {
	isColorSupported: boolean
	reset: Formatter
	bold: Formatter
	dim: Formatter
	italic: Formatter
	underline: Formatter
	inverse: Formatter
	hidden: Formatter
	strikethrough: Formatter
	black: Formatter
	red: Formatter
	green: Formatter
	yellow: Formatter
	blue: Formatter
	magenta: Formatter
	cyan: Formatter
	white: Formatter
	gray: Formatter
	bgBlack: Formatter
	bgRed: Formatter
	bgGreen: Formatter
	bgYellow: Formatter
	bgBlue: Formatter
	bgMagenta: Formatter
	bgCyan: Formatter
	bgWhite: Formatter
}


code:
# PostCSS [![Gitter][chat-img]][chat]

[chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg
[chat]:     https://gitter.im/postcss/postcss

PostCSS is a tool for transforming styles with JS plugins.
These plugins can lint your CSS, support variables and mixins,
transpile future CSS syntax, inline images, and more.

PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
and JetBrains. The [Autoprefixer] PostCSS plugin is one of the most popular
CSS processors.

PostCSS takes a CSS file and provides an API to analyze and modify its rules
(by transforming them into an [Abstract Syntax Tree]).
This API can then be used by [plugins] to do a lot of useful things,
e.g. to find errors automatically insert vendor prefixes.

**Support / Discussion:** [Gitter](https://gitter.im/postcss/postcss)

**Twitter account:**      [@postcss](https://twitter.com/postcss)

**VK.com page:**          [postcss](https://vk.com/postcss)

**中文翻译**:              [`README-cn.md`](./README-cn.md)

For PostCSS commercial support (consulting, improving the front-end culture
of your company, PostCSS plugins), contact [Evil Martians]
at <surrender@evilmartians.com>.

[Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
[Evil Martians]:        https://evilmartians.com/?utm_source=postcss
[Autoprefixer]:         https://github.com/postcss/autoprefixer
[plugins]:              https://github.com/postcss/postcss#plugins

## Docs
Read **[full docs](https://github.com/postcss/postcss#readme)** on GitHub.