file = fs.readFileSync(filepath, 'utf8'); } catch (e) { file = ''; } files.push({name: filepath, contents: file}); }); return files; } var parseFromFiles_1 = function (filepath, files, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); resolve(parseFromFiles(filepath, files, options)); }); }; var parseFromFilesSync_1 = function (filepath, files, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); return parseFromFilesSync(filepath, files, options); }; var parse$6 = function (filepath, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFiles(filepaths); resolve(parseFromFiles(filepath, files, options)); }); }; var parseSync = function (filepath, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFilesSync(filepaths); return parseFromFilesSync(filepath, files, options); }; var parseString = ini.parseString; var editorconfig = { parseFromFiles: parseFromFiles_1, parseFromFilesSync: parseFromFilesSync_1, parse: parse$6, parseSync: parseSync, parseString: parseString }; var editorconfigToPrettier = editorConfigToPrettier; function editorConfigToPrettier(editorConfig) { if (!editorConfig || Object.keys(editorConfig).length === 0) { return null; } const result = {}; if (editorConfig.indent_style) { result.useTabs = editorConfig.indent_style === "tab"; } if (editorConfig.indent_size === "tab") { result.useTabs = true; } if (result.useTabs && editorConfig.tab_width) { result.tabWidth = editorConfig.tab_width; } else if ( editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab" ) { result.tabWidth = editorConfig.indent_size; } else if (editorConfig.tab_width !== undefined) { result.tabWidth = editorConfig.tab_width; } if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") { result.printWidth = editorConfig.max_line_length; } if (editorConfig.quote_type === "single") { result.singleQuote = true; } else if (editorConfig.quote_type === "double") { result.singleQuote = false; } return result; } function markerExists (files, markers) { return markers.some(function(marker) { return files.some(function(file) { return file === marker; }); }); } function traverseFolder (directory, levels, markers) { var files = fs.readdirSync(directory); if (levels === 0) { return null; } else if (markerExists(files, markers)) { return directory; } else { return traverseFolder(path.resolve(directory, '..'), levels - 1, markers); } } var findProjectRoot = function findRoot(dir, opts) { if (!dir) throw new Error("Directory not defined"); opts = opts || {}; var levels = opts.maxDepth || findRoot.MAX_DEPTH; var markers = opts.markers || findRoot.MARKERS; return traverseFolder(dir, levels, markers); }; var MAX_DEPTH = 9; var MARKERS = [ '.git', '.hg' ]; findProjectRoot.MAX_DEPTH = MAX_DEPTH; findProjectRoot.MARKERS = MARKERS; var resolveConfigEditorconfig = createCommonjsModule(function (module) { "use strict"; const maybeParse = (filePath, config, parse) => { const root = findProjectRoot(path.dirname(path.resolve(filePath))); return filePath && parse(filePath, { root }); }; const editorconfigAsyncNoCache = (filePath, config) => { return Promise.resolve(maybeParse(filePath, config, editorconfig.parse)).then( editorconfigToPrettier ); }; const editorconfigAsyncWithCache = mem(editorconfigAsyncNoCache); const editorconfigSyncNoCache = (filePath, config) => { return editorconfigToPrettier( maybeParse(filePath, config, editorconfig.parseSync) ); }; const editorconfigSyncWithCache = mem(editorconfigSyncNoCache); function getLoadFunction(opts) { if (!opts.editorconfig) { return () => null; } if (opts.sync) { return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache; } return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache; } function clearCache() { mem.clear(editorconfigSyncWithCache); mem.clear(editorconfigAsyncWithCache); } module.exports = { getLoadFunction, clearCache }; }); var thirdParty$1 = ( thirdParty && thirdParty__default ) || thirdParty; var resolveConfig_1 = createCommonjsModule(function (module) { "use strict"; const getExplorerMemoized = mem(opts => thirdParty$1.cosmiconfig("prettier", { sync: opts.sync, cache: opts.cache, rcExtensions: true, transform: result => { if (result && result.config) { delete result.config.$schema; } return result; } }) ); /** @param {{ cache: boolean, sync: boolean }} opts */ function getLoadFunction(opts) { // Normalize opts before passing to a memoized function opts = Object.assign({ sync: false, cache: false }, opts); return getExplorerMemoized(opts).load; } function _resolveConfig(filePath, opts, sync) { opts = Object.assign({ useCache: true }, opts); const loadOpts = { cache: !!opts.useCache, sync: !!sync, editorconfig: !!opts.editorconfig }; const load = getLoadFunction(loadOpts); const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts); const arr = [load, loadEditorConfig].map(l => l(filePath, opts.config)); const unwrapAndMerge = arr => { const result = arr[0]; const editorConfigured = arr[1]; const merged = Object.assign( {}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath) ); if (!result && !editorConfigured) { return null; } return merged; }; if (loadOpts.sync) { return unwrapAndMerge(arr); } return Promise.all(arr).then(unwrapAndMerge); } const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false); resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true); function clearCache() { mem.clear(getExplorerMemoized); resolveConfigEditorconfig.clearCache(); } function resolveConfigFile(filePath) { const load = getLoadFunction({ sync: false }); return load(filePath).then(result => { return result ? result.filepath : null; }); } resolveConfigFile.sync = filePath => { const load = getLoadFunction({ sync: true }); const result = load(filePath); return result ? result.filepath : null; }; function mergeOverrides(configResult, filePath) { const options = Object.assign({}, configResult.config); if (filePath && options.overrides) { const relativeFilePath = path.relative( path.dirname(configResult.filepath), filePath ); for (const override of options.overrides) { if ( pathMatchesGlobs( relativeFilePath, override.files, override.excludeFiles ) ) { Object.assign(options, override.options); } } } delete options.overrides; return options; } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js function pathMatchesGlobs(filePath, patterns, excludedPatterns) { const patternList = [].concat(patterns); const excludedPatternList = [].concat(excludedPatterns || []); const opts = { matchBase: true }; return ( patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts) ) ); } module.exports = { resolveConfig, resolveConfigFile, clearCache }; }); const version = require$$0$11.version; const getSupportInfo = support.getSupportInfo; const normalizeOptions = options$12.normalize; const printDocToString = doc.printer.printDocToString; const printDocToDebug = doc.debug.printDocToDebug; function guessLineEnding(text) { const index = text.indexOf("\n"); if (index >= 0 && text.charAt(index - 1) === "\r") { return "\r\n"; } return "\n"; } function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; comments.attach(astComments, ast, text, opts); } ast.tokens = []; opts.originalText = text.trimRight(); return astComments; } function hasPragma(text) { const pragmas = Object.keys(build.parse(build.extract(text))); return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1; } function ensureAllCommentsPrinted(astComments) { if (!astComments) { return; } for (let i = 0; i < astComments.length; ++i) { if (astComments[i].value.trim() === "prettier-ignore") { // If there's a prettier-ignore, we're not printing that sub-tree so we // don't know if the comments was printed or not. return; } } astComments.forEach(comment => { if (!comment.printed) { throw new Error( 'Comment "' + comment.value.trim() + '" was not printed. Please report this error!' ); } delete comment.printed; }); } function formatWithCursor(text, opts, addAlignmentSize) { if (opts.requirePragma && !hasPragma(text)) { return { formatted: text }; } const UTF8BOM = 0xfeff; const hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM; if (hasUnicodeBOM) { text = text.substring(1); } if ( opts.insertPragma && !hasPragma(text) && opts.rangeStart === 0 && opts.rangeEnd === Infinity ) { const parsedDocblock = build.parseWithComments(build.extract(text)); const pragmas = Object.assign({ format: "" }, parsedDocblock.pragmas); const newDocblock = build.print({ pragmas, comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines }); const strippedText = build.strip(text); const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; text = newDocblock + separatingNewlines + strippedText; } addAlignmentSize = addAlignmentSize || 0; const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; const formattedRangeOnly = formatRange(text, opts, ast); if (formattedRangeOnly) { return { formatted: formattedRangeOnly }; } let cursorOffset; if (opts.cursorOffset >= 0) { const cursorNodeAndParents = findNodeAtOffset(ast, opts.cursorOffset, opts); const cursorNode = cursorNodeAndParents.node; if (cursorNode) { cursorOffset = opts.cursorOffset - opts.locStart(cursorNode); opts.cursorNode = cursorNode; } } const astComments = attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts, addAlignmentSize); opts.newLine = guessLineEnding(text); const toStringResult = printDocToString(doc$$1, opts); let str = toStringResult.formatted; if (hasUnicodeBOM) { str = String.fromCharCode(UTF8BOM) + str; } const cursorOffsetResult = toStringResult.cursor; ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { return { formatted: str.trim() + opts.newLine }; } if (cursorOffset !== undefined) { return { formatted: str, cursorOffset: cursorOffsetResult + cursorOffset }; } return { formatted: str }; } function format(text, opts, addAlignmentSize) { return formatWithCursor(text, opts, addAlignmentSize).formatted; } function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, endNode: resultEndNode }; } for (const endParent of endNodeAndParents.parentNodes) { if ( endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node) ) { resultEndNode = endParent; } else { break; } } for (const startParent of startNodeAndParents.parentNodes) { if ( startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node) ) { resultStartNode = startParent; } else { break; } } return { startNode: resultStartNode, endNode: resultEndNode }; } function findNodeAtOffset(node, offset, options, predicate, parentNodes) { predicate = predicate || (() => true); parentNodes = parentNodes || []; const start = options.locStart(node, options.locStart); const end = options.locEnd(node, options.locEnd); if (start <= offset && offset <= end) { for (const childNode of comments.getSortedChildNodes( node, undefined /* text */, options )) { const childResult = findNodeAtOffset( childNode, offset, options, predicate, [node].concat(parentNodes) ); if (childResult) { return childResult; } } if (predicate(node)) { return { node: node, parentNodes: parentNodes }; } } } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 function isSourceElement(opts, node) { if (node == null) { return false; } // JS and JS like to avoid repetitions const jsSourceElements = [ "FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 "ImportDeclaration", // Module "ExportDefaultDeclaration", // Module "ExportNamedDeclaration", // Module "ExportAllDeclaration", // Module "TypeAlias", // Flow "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript "ExportDeclaration" // TypeScript ]; const jsonSourceElements = [ "ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral" ]; const graphqlSourceElements = [ "OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition" ]; switch (opts.parser) { case "flow": case "babylon": case "typescript": return jsSourceElements.indexOf(node.type) > -1; case "json": return jsonSourceElements.indexOf(node.type) > -1; case "graphql": return graphqlSourceElements.indexOf(node.kind) > -1; } return false; } function calculateRange(text, opts, ast) { // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); const startNonWhitespace = Math.max( opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart ); let endNonWhitespace; for ( endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace ) { if (text[endNonWhitespace - 1].match(/\S/)) { break; } } const startNodeAndParents = findNodeAtOffset( ast, startNonWhitespace, opts, node => isSourceElement(opts, node) ); const endNodeAndParents = findNodeAtOffset( ast, endNonWhitespace, opts, node => isSourceElement(opts, node) ); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, rangeEnd: 0 }; } const siblingAncestors = findSiblingAncestors( startNodeAndParents, endNodeAndParents, opts ); const startNode = siblingAncestors.startNode; const endNode = siblingAncestors.endNode; const rangeStart = Math.min( opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart) ); const rangeEnd = Math.max( opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd) ); return { rangeStart: rangeStart, rangeEnd: rangeEnd }; } function formatRange(text, opts, ast) { if (opts.rangeStart <= 0 && text.length <= opts.rangeEnd) { return; } const range = calculateRange(text, opts, ast); const rangeStart = range.rangeStart; const rangeEnd = range.rangeEnd; const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. // This is so we can detect indentation correctly and restore it. // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min( rangeStart, text.lastIndexOf("\n", rangeStart) + 1 ); const indentString = text.slice(rangeStart2, rangeStart); const alignmentSize = util$1.getAlignmentSize( indentString, opts.tabWidth ); const rangeFormatted = format( rangeString, Object.assign({}, opts, { rangeStart: 0, rangeEnd: Infinity, printWidth: opts.printWidth - alignmentSize }), alignmentSize ); // Since the range contracts to avoid trailing whitespace, // we need to remove the newline that was inserted by the `format` call. const rangeTrimmed = rangeFormatted.trimRight(); return text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd); } var prettier$2 = { formatWithCursor: function(text, opts) { return formatWithCursor(text, normalizeOptions(opts)); }, format: function(text, opts) { return format(text, normalizeOptions(opts)); }, check: function(text, opts) { try { const formatted = format(text, normalizeOptions(opts)); return formatted === text; } catch (e) { return false; } }, doc, resolveConfig: resolveConfig_1.resolveConfig, clearConfigCache: resolveConfig_1.clearCache, getSupportInfo, version, util: utilShared, /* istanbul ignore next */ __debug: { parse: function(text, opts) { opts = normalizeOptions(opts); return parser$3.parse(text, opts); }, formatAST: function(ast, opts) { opts = normalizeOptions(opts); const doc$$1 = astToDoc(ast, opts); const str = printDocToString(doc$$1, opts); return str; }, // Doesn't handle shebang for now formatDoc: function(doc$$1, opts) { opts = normalizeOptions(opts); const debug = printDocToDebug(doc$$1); const str = format(debug, opts); return str; }, printToDoc: function(text, opts) { opts = normalizeOptions(opts); const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts); return doc$$1; }, printDocToString: function(doc$$1, opts) { opts = normalizeOptions(opts); const str = printDocToString(doc$$1, opts); return str; } } }; var at; var ch; var escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }; var text; var error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text }; }; var next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }; var number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error("Bad number"); } else { return number; } }; var string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }; var white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }; var word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }; var value; var array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }; var object = function () { // Parse an object value. var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. var parse$8 = function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({'': result}, '')) : result; }; var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; var gap; var indent$8; var meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; var rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); case 'object': if (!value) return 'null'; gap += indent$8; partial = []; // Array.isArray if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and // wrap them in brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be // stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } var stringify$1 = function (value, replacer, space) { var i; gap = ''; indent$8 = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent$8 += ' '; } } // If the space parameter is a string, it will be used as the indent string. else if (typeof space === 'string') { indent$8 = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; var parse$7 = parse$8; var stringify = stringify$1; var jsonify = { parse: parse$7, stringify: stringify }; var json = typeof JSON !== 'undefined' ? JSON : jsonify; var jsonStableStringify = function (obj, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; var space = opts.space || ''; if (typeof space === 'number') space = Array(space+1).join(' '); var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var replacer = opts.replacer || function(key, value) { return value; }; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; })(opts.cmp); var seen = []; return (function stringify (parent, key, node, level) { var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; var colonSeparator = space ? ': ' : ':'; if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } node = replacer.call(parent, key, node); if (node === undefined) { return; } if (typeof node !== 'object' || node === null) { return json.stringify(node); } if (isArray$1(node)) { var out = []; for (var i = 0; i < node.length; i++) { var item = stringify(node, i, node[i], level+1) || json.stringify(null); out.push(indent + space + item); } return '[' + out.join(',') + indent + ']'; } else { if (seen.indexOf(node) !== -1) { if (cycles) return json.stringify('__cycle__'); throw new TypeError('Converting circular structure to JSON'); } else seen.push(node); var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level+1); if(!value) continue; var keyValue = json.stringify(key) + colonSeparator + value; out.push(indent + space + keyValue); } seen.splice(seen.indexOf(node), 1); return '{' + out.join(',') + indent + '}'; } })({ '': obj }, '', obj, 0); }; var isArray$1 = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true }; var keys = []; for (var key in obj) { if (has.call(obj, key)) keys.push(key); } return keys; }; function preserveCamelCase(str) { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i = 0; i < str.length; i++) { const c = str[i]; if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { str = str.substr(0, i) + '-' + str.substr(i); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i++; } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { str = str.substr(0, i - 1) + '-' + str.substr(i - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = c.toLowerCase() === c; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = c.toUpperCase() === c; } } return str; } var camelcase = function (str) { if (arguments.length > 1) { str = Array.from(arguments) .map(x => x.trim()) .filter(x => x.length) .join('-'); } else { str = str.trim(); } if (str.length === 0) { return ''; } if (str.length === 1) { return str.toLowerCase(); } if (/^[a-z0-9]+$/.test(str)) { return str; } const hasUpperCase = str !== str.toLowerCase(); if (hasUpperCase) { str = preserveCamelCase(str); } return str .replace(/^[_.\- ]+/, '') .toLowerCase() .replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase()); }; /*! * dashify <https://github.com/jonschlinkert/dashify> * * Copyright (c) 2015 Jon Schlinkert. * Licensed under the MIT license. */ var dashify = function dashify(str) { if (typeof str !== 'string') { throw new TypeError('expected a string'); } str = str.replace(/([a-z])([A-Z])/g, '$1-$2'); str = str.replace(/[ \t\W]/g, '-'); str = str.replace(/^-+|-+$/g, ''); return str.toLowerCase(); }; var PENDING = 'pending'; var SETTLED = 'settled'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function () {}; var isNode$1 = typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.process !== 'undefined' && typeof commonjsGlobal.process.emit === 'function'; var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; var asyncQueue = []; var asyncTimer; function asyncFlush() { // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) { asyncQueue[i][0](asyncQueue[i][1]); } // reset async asyncQueue asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg) { asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve$3(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch (e) { rejectPromise(e); } } function invokeCallback(subscriber) { var owner = subscriber.owner; var settled = owner._state; var value = owner._data; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch (e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) { resolve$3(promise, value); } if (settled === REJECTED) { reject(promise, value); } } } function handleThenable(promise, value) { var resolved; try { if (promise === value) { throw new TypeError('A promises callback cannot return that same promise.'); } if (value && (typeof value === 'function' || typeof value === 'object')) { // then should be retrieved only once var then = value.then; if (typeof then === 'function') { then.call(value, function (val) { if (!resolved) { resolved = true; if (value === val) { fulfill(promise, val); } else { resolve$3(promise, val); } } }, function (reason) { if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) { reject(promise, e); } return true; } return false; } function resolve$3(promise, value) { if (promise === value || !handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = reason; asyncCall(publishRejection, promise); } } function publish(promise) { promise._then = promise._then.forEach(invokeCallback); } function publishFulfillment(promise) { promise._state = FULFILLED; publish(promise); } function publishRejection(promise) { promise._state = REJECTED; publish(promise); if (!promise._handled && isNode$1) { commonjsGlobal.process.emit('unhandledRejection', promise._data, promise); } } function notifyRejectionHandled(promise) { commonjsGlobal.process.emit('rejectionHandled', promise); } /** * @class */ function Promise$2(resolver) { if (typeof resolver !== 'function') { throw new TypeError('Promise resolver ' + resolver + ' is not a function'); } if (this instanceof Promise$2 === false) { throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); } this._then = []; invokeResolver(resolver, this); } Promise$2.prototype = { constructor: Promise$2, _state: PENDING, _then: null, _data: undefined, _handled: false, then: function (onFulfillment, onRejection) { var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if ((onRejection || onFulfillment) && !this._handled) { this._handled = true; if (this._state === REJECTED && isNode$1) { asyncCall(notifyRejectionHandled, this); } } if (this._state === FULFILLED || this._state === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this._then.push(subscriber); } return subscriber.then; }, catch: function (onRejection) { return this.then(null, onRejection); } }; Promise$2.all = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.all().'); } return new Promise$2(function (resolve, reject) { var results = []; var remaining = 0; function resolver(index) { remaining++; return function (value) { results[index] = value; if (!--remaining) { resolve(results); } }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolver(i), reject); } else { results[i] = promise; } } if (!remaining) { resolve(results); } }); }; Promise$2.race = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.race().'); } return new Promise$2(function (resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); }; Promise$2.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise$2) { return value; } return new Promise$2(function (resolve) { resolve(value); }); }; Promise$2.reject = function (reason) { return new Promise$2(function (resolve, reject) { reject(reason); }); }; var pinkie = Promise$2; var pinkiePromise = typeof Promise === 'function' ? Promise : pinkie; var arrayUniq = createCommonjsModule(function (module) { 'use strict'; // there's 3 implementations written in increasing order of efficiency // 1 - no Set type is defined function uniqNoSet(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (ret.indexOf(arr[i]) === -1) { ret.push(arr[i]); } } return ret; } // 2 - a simple Set type is defined function uniqSet(arr) { var seen = new Set(); return arr.filter(function (el) { if (!seen.has(el)) { seen.add(el); return true; } return false; }); } // 3 - a standard Set type is defined and it has a forEach method function uniqSetWithForEach(arr) { var ret = []; (new Set(arr)).forEach(function (el) { ret.push(el); }); return ret; } // V8 currently has a broken implementation // https://github.com/joyent/node/issues/8449 function doesForEachActuallyWork() { var ret = false; (new Set([true])).forEach(function (el) { ret = el; }); return ret === true; } if ('Set' in commonjsGlobal) { if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) { module.exports = uniqSetWithForEach; } else { module.exports = uniqSet; } } else { module.exports = uniqNoSet; } }); var arrayUnion = function () { return arrayUniq([].concat.apply([], arguments)); }; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty$1 = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty$1.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var isWindows = process.platform === 'win32'; // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } var realpathSync$1 = function realpathSync(p, cache) { // make p is absolute p = path.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = path.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = path.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; var realpath$1 = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = path.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = path.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = path.resolve(resolvedLink, p.slice(pos)); start(); } }; var old$1 = { realpathSync: realpathSync$1, realpath: realpath$1 }; var fs_realpath = realpath; realpath.realpath = realpath; realpath.sync = realpathSync; realpath.realpathSync = realpathSync; realpath.monkeypatch = monkeypatch; realpath.unmonkeypatch = unmonkeypatch; var origRealpath = fs.realpath; var origRealpathSync = fs.realpathSync; var version$3 = process.version; var ok = /^v[0-5]\./.test(version$3); function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache; cache = null; } origRealpath(p, cache, function (er, result) { if (newError(er)) { old$1.realpath(p, cache, cb); } else { cb(er, result); } }); } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old$1.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath; fs.realpathSync = realpathSync; } function unmonkeypatch () { fs.realpath = origRealpath; fs.realpathSync = origRealpathSync; } var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var inherits$2 = createCommonjsModule(function (module) { try { var util$$2 = util; if (typeof util$$2.inherits !== 'function') throw ''; module.exports = util$$2.inherits; } catch (e) { module.exports = inherits_browser; } }); function posix(path$$1) { return path$$1.charAt(0) === '/'; } function win32(path$$1) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path$$1); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } var pathIsAbsolute = process.platform === 'win32' ? win32 : posix; var posix_1 = posix; var win32_1 = win32; pathIsAbsolute.posix = posix_1; pathIsAbsolute.win32 = win32_1; var alphasort_1 = alphasort$2; var alphasorti_1 = alphasorti$2; var setopts_1 = setopts$2; var ownProp_1 = ownProp$2; var makeAbs_1 = makeAbs; var finish_1 = finish; var mark_1 = mark; var isIgnored_1 = isIgnored$2; var childrenIgnored_1 = childrenIgnored$2; function ownProp$2 (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var Minimatch$3 = minimatch_1.Minimatch; function alphasorti$2 (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort$2 (a, b) { return a.localeCompare(b) } function setupIgnores (self, options) { self.ignore = options.ignore || []; if (!Array.isArray(self.ignore)) self.ignore = [self.ignore]; if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap); } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null; if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, ''); gmatcher = new Minimatch$3(gpattern, { dot: true }); } return { matcher: new Minimatch$3(pattern, { dot: true }), gmatcher: gmatcher } } function setopts$2 (self, pattern, options) { if (!options) options = {}; // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern; } self.silent = !!options.silent; self.pattern = pattern; self.strict = options.strict !== false; self.realpath = !!options.realpath; self.realpathCache = options.realpathCache || Object.create(null); self.follow = !!options.follow; self.dot = !!options.dot; self.mark = !!options.mark; self.nodir = !!options.nodir; if (self.nodir) self.mark = true; self.sync = !!options.sync; self.nounique = !!options.nounique; self.nonull = !!options.nonull; self.nosort = !!options.nosort; self.nocase = !!options.nocase; self.stat = !!options.stat; self.noprocess = !!options.noprocess; self.absolute = !!options.absolute; self.maxLength = options.maxLength || Infinity; self.cache = options.cache || Object.create(null); self.statCache = options.statCache || Object.create(null); self.symlinks = options.symlinks || Object.create(null); setupIgnores(self, options); self.changedCwd = false; var cwd = process.cwd(); if (!ownProp$2(options, "cwd")) self.cwd = cwd; else { self.cwd = path.resolve(options.cwd); self.changedCwd = self.cwd !== cwd; } self.root = options.root || path.resolve(self.cwd, "/"); self.root = path.resolve(self.root); if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); self.nomount = !!options.nomount; // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true; options.nocomment = true; self.minimatch = new Minimatch$3(pattern, options); self.options = self.minimatch.options; } function finish (self) { var nou = self.nounique; var all = nou ? [] : Object.create(null); for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i]; if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i]; if (nou) all.push(literal); else all[literal] = true; } } else { // had matches var m = Object.keys(matches); if (nou) all.push.apply(all, m); else m.forEach(function (m) { all[m] = true; }); } } if (!nou) all = Object.keys(all); if (!self.nosort) all = all.sort(self.nocase ? alphasorti$2 : alphasort$2); // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]); } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)); var c = self.cache[e] || self.cache[makeAbs(self, e)]; if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c); return notDir }); } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored$2(self, m) }); self.found = all; } function mark (self, p) { var abs = makeAbs(self, p); var c = self.cache[abs]; var m = p; if (c) { var isDir = c === 'DIR' || Array.isArray(c); var slash = p.slice(-1) === '/'; if (isDir && !slash) m += '/'; else if (!isDir && slash) m = m.slice(0, -1); if (m !== p) { var mabs = makeAbs(self, m); self.statCache[mabs] = self.statCache[abs]; self.cache[mabs] = self.cache[abs]; } } return m } // lotta situps... function makeAbs (self, f) { var abs = f; if (f.charAt(0) === '/') { abs = path.join(self.root, f); } else if (pathIsAbsolute(f) || f === '') { abs = f; } else if (self.changedCwd) { abs = path.resolve(self.cwd, f); } else { abs = path.resolve(f); } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/'); return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored$2 (self, path$$2) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path$$2) || !!(item.gmatcher && item.gmatcher.match(path$$2)) }) } function childrenIgnored$2 (self, path$$2) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path$$2)) }) } var common = { alphasort: alphasort_1, alphasorti: alphasorti_1, setopts: setopts_1, ownProp: ownProp_1, makeAbs: makeAbs_1, finish: finish_1, mark: mark_1, isIgnored: isIgnored_1, childrenIgnored: childrenIgnored_1 }; var sync$4 = globSync; globSync.GlobSync = GlobSync$1; var setopts$1 = common.setopts; var ownProp$1 = common.ownProp; var childrenIgnored$1 = common.childrenIgnored; var isIgnored$1 = common.isIgnored; function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync$1(pattern, options).found } function GlobSync$1 (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync$1)) return new GlobSync$1(pattern, options) setopts$1(this, pattern, options); if (this.noprocess) return this var n = this.minimatch.set.length; this.matches = new Array(n); for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false); } this._finish(); } GlobSync$1.prototype._finish = function () { assert(this instanceof GlobSync$1); if (this.realpath) { var self = this; this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null); for (var p in matchset) { try { p = self._makeAbs(p); var real = fs_realpath.realpathSync(p, self.realpathCache); set[real] = true; } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true; else throw er } } }); } common.finish(this); }; GlobSync$1.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync$1); // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip processing if (childrenIgnored$1(this, read)) return var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar); }; GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; var newPattern; if (prefix) newPattern = [prefix, e]; else newPattern = [e]; this._process(newPattern.concat(remain), index, inGlobStar); } }; GlobSync$1.prototype._emitMatch = function (index, e) { if (isIgnored$1(this, e)) return var abs = this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) { e = abs; } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; if (this.stat) this._stat(e); }; GlobSync$1.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries; var lstat; var stat; try { lstat = fs.lstatSync(abs); } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink(); this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE'; else entries = this._readdir(abs, false); return entries }; GlobSync$1.prototype._readdir = function (abs, inGlobStar) { var entries; if (inGlobStar && !ownProp$1(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp$1(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er); return null } }; GlobSync$1.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; // mark and cache dir-ness return entries }; GlobSync$1.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) throw er if (!this.silent) console.error('glob error', er); break } }; GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false); var len = entries.length; var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true); var below = gspref.concat(entries[i], remain); this._process(below, index, true); } }; GlobSync$1.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix); if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && pathIsAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); }; // Returns either 'DIR', 'FILE', or false GlobSync$1.prototype._stat = function (f) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return false if (!this.stat && ownProp$1(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists; var stat = this.statCache[abs]; if (!stat) { var lstat; try { lstat = fs.lstatSync(abs); } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = fs.statSync(abs); } catch (er) { stat = lstat; } } else { stat = lstat; } } this.statCache[abs] = stat; var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return false return c }; GlobSync$1.prototype._mark = function (p) { return common.mark(this, p) }; GlobSync$1.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. var wrappy_1 = wrappy; function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k]; }); return wrapper function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb = args[args.length-1]; if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k]; }); } return ret } } var once_1 = wrappy_1(once); var strict = wrappy_1(onceStrict); once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }); Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }); }); function once (fn) { var f = function () { if (f.called) return f.value f.called = true; return f.value = fn.apply(this, arguments) }; f.called = false; return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true; return f.value = fn.apply(this, arguments) }; var name = fn.name || 'Function wrapped with `once`'; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f } once_1.strict = strict; var reqs = Object.create(null); var inflight_1 = wrappy_1(inflight); function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb); return null } else { reqs[key] = [cb]; return makeres(key) } } function makeres (key) { return once_1(function RES () { var cbs = reqs[key]; var len = cbs.length; var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args); } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len); process.nextTick(function () { RES.apply(null, args); }); } else { delete reqs[key]; } } }) } function slice (args) { var length = args.length; var array = []; for (var i = 0; i < length; i++) array[i] = args[i]; return array } // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. var glob_1 = glob; var EE = events.EventEmitter; var setopts = common.setopts; var ownProp = common.ownProp; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {}; if (!options) options = {}; if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return sync$4(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = sync$4; var GlobSync = glob.GlobSync = sync$4.GlobSync; // old api surface glob.glob = glob; function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_); options.noprocess = true; var g = new Glob(pattern, options); var set = g.minimatch.set; if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false }; glob.Glob = Glob; inherits$2(Glob, EE); function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options; options = null; } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options); this._didRealPath = false; // process each pattern in the minimatch set var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n); if (typeof cb === 'function') { cb = once_1(cb); this.on('error', cb); this.on('end', function (matches) { cb(null, matches); }); } var self = this; this._processing = 0; this._emitQueue = []; this._processQueue = []; this.paused = false; if (this.noprocess) return this if (n === 0) return done() var sync = true; for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done); } sync = false; function done () { --self._processing; if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish(); }); } else { self._finish(); } } } } Glob.prototype._finish = function () { assert(this instanceof Glob); if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this); this.emit('end', this.found); }; Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true; var n = this.matches.length; if (n === 0) return this._finish() var self = this; for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next); function next () { if (--n === 0) self._finish(); } }; Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index]; if (!matchset) return cb() var found = Object.keys(matchset); var self = this; var n = found.length; if (n === 0) return cb() var set = this.matches[index] = Object.create(null); found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p); fs_realpath.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true; else if (er.syscall === 'stat') set[p] = true; else self.emit('error', er); // srsly wtf right here if (--n === 0) { self.matches[index] = set; cb(); } }); }); }; Glob.prototype._mark = function (p) { return common.mark(this, p) }; Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; Glob.prototype.abort = function () { this.aborted = true; this.emit('abort'); }; Glob.prototype.pause = function () { if (!this.paused) { this.paused = true; this.emit('pause'); } }; Glob.prototype.resume = function () { if (this.paused) { this.emit('resume'); this.paused = false; if (this._emitQueue.length) { var eq = this._emitQueue.slice(0); this._emitQueue.length = 0; for (var i = 0; i < eq.length; i ++) { var e = eq[i]; this._emitMatch(e[0], e[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i = 0; i < pq.length; i ++) { var p = pq[i]; this._processing--; this._process(p[0], p[1], p[2], p[3]); } } } }; Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob); assert(typeof cb === 'function'); if (this.aborted) return this._processing++; if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]); return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); }; Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }); }; Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; var newPattern; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } this._process([e].concat(remain), index, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]); return } var abs = pathIsAbsolute(e) ? e : this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) e = abs; if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; var st = this.statCache[abs]; if (st) this.emit('stat', e, st); this.emit('match', e); }; Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs; var self = this; var lstatcb = inflight_1(lstatkey, lstatcb_); if (lstatcb) fs.lstat(abs, lstatcb); function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink(); self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE'; cb(); } else self._readdir(abs, false, cb); } }; Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb); if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this; fs.readdir(abs, readdirCb(this, abs, cb)); }; function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb); else self._readdirEntries(abs, entries, cb); } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; return cb(null, entries) }; Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; this.emit('error', error); this.abort(); } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) { this.emit('error', er); // If the error is handled, then we abort // if not, we threw out of here this.abort(); } if (!this.silent) console.error('glob error', er); break } return cb() }; Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true, cb); var below = gspref.concat(entries[i], remain); this._process(below, index, true, cb); } cb(); }; Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this; this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb); }); }; Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && pathIsAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); cb(); }; // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists; var stat = this.statCache[abs]; if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE'; if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this; var statcb = inflight_1('stat\0' + abs, lstatcb_); if (statcb) fs.lstat(abs, statcb); function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb); else self._stat2(f, abs, er, stat, cb); }) } else { self._stat2(f, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return cb() } var needDir = f.slice(-1) === '/'; this.statCache[abs] = stat; if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }; var pify_1 = createCommonjsModule(function (module) { 'use strict'; var processFn = function (fn, P, opts) { return function () { var that = this; var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } return new P(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else if (opts.multiArgs) { var results = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) { results[i - 1] = arguments[i]; } resolve(results); } else { resolve(result); } }); fn.apply(that, args); }); }; }; var pify = module.exports = function (obj, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } opts = opts || {}; opts.exclude = opts.exclude || [/.+Sync$/]; var filter = function (key) { var match = function (pattern) { return typeof pattern === 'string' ? key === pattern : pattern.test(key); }; return opts.include ? opts.include.some(match) : !opts.exclude.some(match); }; var ret = typeof obj === 'function' ? function () { if (opts.excludeMain) { return obj.apply(this, arguments); } return processFn(obj, P, opts).apply(this, arguments); } : {}; return Object.keys(obj).reduce(function (ret, key) { var x = obj[key]; ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; return ret; }, ret); }; pify.all = pify; }); var globP = pify_1(glob_1, pinkiePromise).bind(glob_1); function isNegative(pattern) { return pattern[0] === '!'; } function isString(value) { return typeof value === 'string'; } function assertPatternsInput(patterns) { if (!patterns.every(isString)) { throw new TypeError('patterns must be a string or an array of strings'); } } function generateGlobTasks(patterns, opts) { patterns = [].concat(patterns); assertPatternsInput(patterns); var globTasks = []; opts = objectAssign({ cache: Object.create(null), statCache: Object.create(null), realpathCache: Object.create(null), symlinks: Object.create(null), ignore: [] }, opts); patterns.forEach(function (pattern, i) { if (isNegative(pattern)) { return; } var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) { return pattern.slice(1); }); globTasks.push({ pattern: pattern, opts: objectAssign({}, opts, { ignore: opts.ignore.concat(ignore) }) }); }); return globTasks; } var globby = function (patterns, opts) { var globTasks; try { globTasks = generateGlobTasks(patterns, opts); } catch (err) { return pinkiePromise.reject(err); } return pinkiePromise.all(globTasks.map(function (task) { return globP(task.pattern, task.opts); })).then(function (paths) { return arrayUnion.apply(null, paths); }); }; var sync$3 = function (patterns, opts) { var globTasks = generateGlobTasks(patterns, opts); return globTasks.reduce(function (matches, task) { return arrayUnion(matches, glob_1.sync(task.pattern, task.opts)); }, []); }; var generateGlobTasks_1 = generateGlobTasks; var hasMagic = function (patterns, opts) { return [].concat(patterns).some(function (pattern) { return glob_1.hasMagic(pattern, opts); }); }; globby.sync = sync$3; globby.generateGlobTasks = generateGlobTasks_1; globby.hasMagic = hasMagic; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ignore = function () { return new IgnoreBase(); }; // A simple implementation of make-array function make_array(subject) { return Array.isArray(subject) ? subject : [subject]; } var REGEX_BLANK_LINE = /^\s+$/; var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\\!/; var REGEX_LEADING_EXCAPED_HASH = /^\\#/; var SLASH = '/'; var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') /* istanbul ignore next */ : 'node-ignore'; var IgnoreBase = function () { function IgnoreBase() { _classCallCheck(this, IgnoreBase); this._rules = []; this[KEY_IGNORE] = true; this._initCache(); } _createClass(IgnoreBase, [{ key: '_initCache', value: function _initCache() { this._cache = {}; } // @param {Array.<string>|string|Ignore} pattern }, { key: 'add', value: function add(pattern) { this._added = false; if (typeof pattern === 'string') { pattern = pattern.split(/\r?\n/g); } make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, // making the behavior changed. if (this._added) { this._initCache(); } return this; } // legacy }, { key: 'addPattern', value: function addPattern(pattern) { return this.add(pattern); } }, { key: '_addPattern', value: function _addPattern(pattern) { // #32 if (pattern && pattern[KEY_IGNORE]) { this._rules = this._rules.concat(pattern._rules); this._added = true; return; } if (this._checkPattern(pattern)) { var rule = this._createRule(pattern); this._added = true; this._rules.push(rule); } } }, { key: '_checkPattern', value: function _checkPattern(pattern) { // > A blank line matches no files, so it can serve as a separator for readability. return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. && pattern.indexOf('#') !== 0; } }, { key: 'filter', value: function filter(paths) { var _this = this; return make_array(paths).filter(function (path$$1) { return _this._filter(path$$1); }); } }, { key: 'createFilter', value: function createFilter() { var _this2 = this; return function (path$$1) { return _this2._filter(path$$1); }; } }, { key: 'ignores', value: function ignores(path$$1) { return !this._filter(path$$1); } }, { key: '_createRule', value: function _createRule(pattern) { var origin = pattern; var negative = false; // > An optional prefix "!" which negates the pattern; if (pattern.indexOf('!') === 0) { negative = true; pattern = pattern.substr(1); } pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, `"\!important!.txt"`. .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that begin with a hash. .replace(REGEX_LEADING_EXCAPED_HASH, '#'); var regex = make_regex(pattern, negative); return { origin: origin, pattern: pattern, negative: negative, regex: regex }; } // @returns `Boolean` true if the `path` is NOT ignored }, { key: '_filter', value: function _filter(path$$1, slices) { if (!path$$1) { return false; } if (path$$1 in this._cache) { return this._cache[path$$1]; } if (!slices) { // path/to/a.js // ['path', 'to', 'a.js'] slices = path$$1.split(SLASH); } slices.pop(); return this._cache[path$$1] = slices.length // > It is not possible to re-include a file if a parent directory of that file is excluded. // If the path contains a parent directory, check the parent first ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path$$1) // Or only test the path : this._test(path$$1); } // @returns {Boolean} true if a file is NOT ignored }, { key: '_test', value: function _test(path$$1) { // Explicitly define variable type by setting matched to `0` var matched = 0; this._rules.forEach(function (rule) { // if matched = true, then we only test negative rules // if matched = false, then we test non-negative rules if (!(matched ^ rule.negative)) { matched = rule.negative ^ rule.regex.test(path$$1); } }); return !matched; } }]); return IgnoreBase; }(); // > If the pattern ends with a slash, // > it is removed for the purpose of the following description, // > but it would only find a match with a directory. // > In other words, foo/ will match a directory foo and paths underneath it, // > but will not match a regular file or a symbolic link foo // > (this is consistent with the way how pathspec works in general in Git). // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call // you could use option `mark: true` with `glob` // '`foo/`' should not continue with the '`..`' var DEFAULT_REPLACER_PREFIX = [ // > Trailing spaces are ignored unless they are quoted with backslash ("\") [ // (a\ ) -> (a ) // (a ) -> (a) // (a \ ) -> (a ) /\\?\s+$/, function (match) { return match.indexOf('\\') === 0 ? ' ' : ''; }], // replace (\ ) with ' ' [/\\\s/g, function () { return ' '; }], // Escape metacharacters // which is written down by users but means special for regular expressions. // > There are 12 characters with special meanings: // > - the backslash \, // > - the caret ^, // > - the dollar sign $, // > - the period or dot ., // > - the vertical bar or pipe symbol |, // > - the question mark ?, // > - the asterisk or star *, // > - the plus sign +, // > - the opening parenthesis (, // > - the closing parenthesis ), // > - and the opening square bracket [, // > - the opening curly brace {, // > These special characters are often called "metacharacters". [/[\\\^$.|?*+()\[{]/g, function (match) { return '\\' + match; }], // leading slash [ // > A leading slash matches the beginning of the pathname. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". // A leading slash matches the beginning of the pathname /^\//, function () { return '^'; }], // replace special metacharacter slash after the leading slash [/\//g, function () { return '\\/'; }], [ // > A leading "**" followed by a slash means match in all directories. // > For example, "**/foo" matches file or directory "foo" anywhere, // > the same as pattern "foo". // > "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo". // Notice that the '*'s have been replaced as '\\*' /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' function () { return '^(?:.*\\/)?'; }]]; var DEFAULT_REPLACER_SUFFIX = [ // starting [ // there will be no leading '/' (which has been replaced by section "leading slash") // If starts with '**', adding a '^' to the regular expression also works /^(?=[^\^])/, function () { return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /, Git treats it as a shell glob pattern // Actually, if there is only a trailing slash, git also treats it as a shell glob pattern ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for consumption by fnmatch(3) : '^'; }], // two globstars [ // Use lookahead assertions so that we could match more than one `'/**'` /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories // should not use '*', or it will be replaced by the next replacer // Check if it is not the last `'/**'` function (match, index, str) { return index + 6 < str.length // case: /**/ // > A slash followed by two consecutive asterisks then a slash matches zero or more directories. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. // '/**/' ? '(?:\\/[^\\/]+)*' // case: /** // > A trailing `"/**"` matches everything inside. // #21: everything inside but it should not include the current folder : '\\/.+'; }], // intermediate wildcards [ // Never replace escaped '*' // ignore rule '\*' will match the path '*' // 'abc.*/' -> go // 'abc.*' -> skip this rule /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js' // '*.js' doesn't match 'abc' function (match, p1) { return p1 + '[^\\/]*'; }], // trailing wildcard [/(\^|\\\/)?\\\*$/, function (match, p1) { return (p1 // '\^': // '/*' does not match '' // '/*' does not match everything // '\\\/': // 'abc/*' does not match 'abc/' ? p1 + '[^/]+' // 'a*' matches 'a' // 'a*' matches 'aa' : '[^/]*') + '(?=$|\\/$)'; }], [ // unescape /\\\\\\/g, function () { return '\\'; }]]; var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [ // 'f' // matches // - /f(end) // - /f/ // - (start)f(end) // - (start)f/ // doesn't match // - oof // - foo // pseudo: // -> (^|/)f(/|$) // ending [ // 'js' will not match 'js.' // 'ab' will not match 'abc' /(?:[^*\/])$/, // 'js*' will not match 'a.js' // 'js/' will not match 'a.js' // 'js' will match 'a.js' and 'a.js/' function (match) { return match + '(?=$|\\/)'; }]], DEFAULT_REPLACER_SUFFIX); var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [ // #24 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore) // A negative pattern without a trailing wildcard should not // re-include the things inside that directory. // eg: // ['node_modules/*', '!node_modules'] // should ignore `node_modules/a.js` [/(?:[^*\/])$/, function (match) { return match + '(?=$|\\/$)'; }]], DEFAULT_REPLACER_SUFFIX); // A simple cache, because an ignore rule only has only one certain meaning var cache = {}; // @param {pattern} function make_regex(pattern, negative) { var r = cache[pattern]; if (r) { return r; } var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS; var source = replacers.reduce(function (prev, current) { return prev.replace(current[0], current[1].bind(pattern)); }, pattern); return cache[pattern] = new RegExp(source, 'i'); } // Windows // -------------------------------------------------------------- /* istanbul ignore if */ if ( // Detect `process` so that it can run in browsers. typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { var filter$3 = IgnoreBase.prototype._filter; var make_posix = function make_posix(str) { return (/^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/') ); }; IgnoreBase.prototype._filter = function (path$$1, slices) { path$$1 = make_posix(path$$1); return filter$3.call(this, path$$1, slices); }; } var ansiStyles$3 = createCommonjsModule(function (module) { 'use strict'; const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert, arguments); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; function assembleStyles() { const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], // Bright color redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Fix humans styles.color.grey = styles.color.gray; Object.keys(styles).forEach(groupName => { const group = styles[groupName]; Object.keys(group).forEach(styleName => { const style = group[styleName]; styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; }); Object.defineProperty(styles, groupName, { value: group, enumerable: false }); }); const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = {}; styles.color.ansi256 = {}; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = {}; styles.bgColor.ansi256 = {}; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (const key of Object.keys(colorConvert)) { if (typeof colorConvert[key] !== 'object') { continue; } const suite = colorConvert[key]; if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); var supportsColor$3 = createCommonjsModule(function (module) { 'use strict'; const env = process.env; const support = level => { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; }; let supportLevel = (() => { if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { return 1; } if (process.stdout && !process.stdout.isTTY) { return 0; } if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. const osRelease = os.release().split('.'); if ( Number(process.version.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return 2; } return 1; } if ('CI' in env) { if ('TRAVIS' in env || env.CI === 'Travis' || 'CIRCLECI' in env) { return 1; } return 0; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Hyper': return 3; case 'Apple_Terminal': return 2; // No default } } if (/^(screen|xterm)-256(?:color)?/.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } if (env.TERM === 'dumb') { return 0; } return 0; })(); if ('FORCE_COLOR' in env) { supportLevel = parseInt(env.FORCE_COLOR, 10) === 0 ? 0 : (supportLevel || 1); } module.exports = process && support(supportLevel); }); var templates$2 = createCommonjsModule(function (module) { 'use strict'; const TEMPLATE_REGEX = /(?:\\(u[a-f0-9]{4}|x[a-f0-9]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[0-9a-f]{4}|x[0-9a-f]{2}|.)|([^\\])/gi; const ESCAPES = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', 0: '\0', '\\': '\\', e: '\u001b', a: '\u0007' }; function unescape(c) { if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES[c] || c; } function parseArguments(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } module.exports = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; }); const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = supportsColor$3 ? supportsColor$3.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles$3.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles$3)) { ansiStyles$3[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles$3[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles$3[key]; return build$1.call(this, this._styles ? this._styles.concat(codes) : [codes], key); } }; } ansiStyles$3.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles$3.color.close), 'g'); for (const model of Object.keys(ansiStyles$3.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles$3.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$3.color.close, closeRe: ansiStyles$3.color.closeRe }; return build$1.call(this, this._styles ? this._styles.concat(codes) : [codes], model); }; } }; } ansiStyles$3.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles$3.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles$3.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles$3.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$3.bgColor.close, closeRe: ansiStyles$3.bgColor.closeRe }; return build$1.call(this, this._styles ? this._styles.concat(codes) : [codes], model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build$1(_styles, key) { const builder = function () { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles$3.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles$3.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles$3.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return templates$2(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); var chalk$2 = Chalk(); // eslint-disable-line new-cap var supportsColor_1 = supportsColor$3; chalk$2.supportsColor = supportsColor_1; var minimist = function (args, opts) { if (!opts) opts = {}; var flags = { bools : {}, strings : {}, unknownFn: null }; if (typeof opts['unknown'] === 'function') { flags.unknownFn = opts['unknown']; } if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { flags.allBools = true; } else { [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { flags.bools[key] = true; }); } var aliases = {}; Object.keys(opts.alias || {}).forEach(function (key) { aliases[key] = [].concat(opts.alias[key]); aliases[key].forEach(function (x) { aliases[x] = [key].concat(aliases[key].filter(function (y) { return x !== y; })); }); }); [].concat(opts.string).filter(Boolean).forEach(function (key) { flags.strings[key] = true; if (aliases[key]) { flags.strings[aliases[key]] = true; } }); var defaults = opts['default'] || {}; var argv = { _ : [] }; Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] === undefined ? false : defaults[key]); }); var notFlags = []; if (args.indexOf('--') !== -1) { notFlags = args.slice(args.indexOf('--')+1); args = args.slice(0, args.indexOf('--')); } function argDefined(key, arg) { return (flags.allBools && /^--[^=]+$/.test(arg)) || flags.strings[key] || flags.bools[key] || aliases[key]; } function setArg (key, val, arg) { if (arg && flags.unknownFn && !argDefined(key, arg)) { if (flags.unknownFn(arg) === false) return; } var value = !flags.strings[key] && isNumber(val) ? Number(val) : val; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), value); }); } function setKey (obj, keys, value) { var o = obj; keys.slice(0,-1).forEach(function (key) { if (o[key] === undefined) o[key] = {}; o = o[key]; }); var key = keys[keys.length - 1]; if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { o[key] = value; } else if (Array.isArray(o[key])) { o[key].push(value); } else { o[key] = [ o[key], value ]; } } function aliasIsBoolean(key) { return aliases[key].some(function (x) { return flags.bools[x]; }); } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (/^--.+=/.test(arg)) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); var key = m[1]; var value = m[2]; if (flags.bools[key]) { value = value !== 'false'; } setArg(key, value, arg); } else if (/^--no-.+/.test(arg)) { var key = arg.match(/^--no-(.+)/)[1]; setArg(key, false, arg); } else if (/^--.+/.test(arg)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) { setArg(key, next, arg); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next === 'true', arg); i++; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } else if (/^-[^-]+/.test(arg)) { var letters = arg.slice(1,-1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { var next = arg.slice(j+2); if (next === '-') { setArg(letters[j], next, arg); continue; } if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { setArg(letters[j], next.split('=')[1], arg); broken = true; break; } if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { setArg(letters[j], next, arg); broken = true; break; } if (letters[j+1] && letters[j+1].match(/\W/)) { setArg(letters[j], arg.slice(j+2), arg); broken = true; break; } else { setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } var key = arg.slice(-1)[0]; if (!broken && key !== '-') { if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) { setArg(key, args[i+1], arg); i++; } else if (args[i+1] && /true|false/.test(args[i+1])) { setArg(key, args[i+1] === 'true', arg); i++; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } } else { if (!flags.unknownFn || flags.unknownFn(arg) !== false) { argv._.push( flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) ); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i + 1)); break; } } } Object.keys(defaults).forEach(function (key) { if (!hasKey(argv, key.split('.'))) { setKey(argv, key.split('.'), defaults[key]); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), defaults[key]); }); } }); if (opts['--']) { argv['--'] = new Array(); notFlags.forEach(function(key) { argv['--'].push(key); }); } else { notFlags.forEach(function(key) { argv._.push(key); }); } return argv; }; function hasKey (obj, keys) { var o = obj; keys.slice(0,-1).forEach(function (key) { o = (o[key] || {}); }); var key = keys[keys.length - 1]; return key in o; } function isNumber (x) { if (typeof x === 'number') return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } const PLACEHOLDER = null; /** * unspecified boolean flag without default value is parsed as `undefined` instead of `false` */ var minimist_1 = function(args, options) { const boolean = options.boolean || []; const defaults = options.default || {}; const booleanWithoutDefault = boolean.filter(key => !(key in defaults)); const newDefaults = Object.assign( {}, defaults, booleanWithoutDefault.reduce( (reduced, key) => Object.assign(reduced, { [key]: PLACEHOLDER }), {} ) ); const parsed = minimist( args, Object.assign({}, options, { default: newDefaults }) ); return Object.keys(parsed).reduce((reduced, key) => { if (parsed[key] !== PLACEHOLDER) { reduced[key] = parsed[key]; } return reduced; }, {}); }; function cleanAST$1(ast, options) { return JSON.stringify(massageAST(ast, options), null, 2); } function massageAST(ast, options, parent) { if (Array.isArray(ast)) { return ast.map(e => massageAST(e, options, parent)).filter(e => e); } if (!ast || typeof ast !== "object") { return ast; } const newObj = {}; for (const key in ast) { if (typeof ast[key] !== "function") { newObj[key] = massageAST(ast[key], options, ast); } } [ "loc", "range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "tokens", "flags", "raws", "sourceIndex", "id", "source", "before", "after", "trailingComma", "parent", "prev", "position" ].forEach(name => { delete newObj[name]; }); if (options.printer.massageAstNode) { const result = options.printer.massageAstNode(ast, newObj, parent); if (result === null) { return undefined; } if (result) { return result; } } return newObj; } var cleanAst = { cleanAST: cleanAST$1, massageAST }; var base = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports['default'] = /*istanbul ignore end*/Diff; function Diff() {} Diff.prototype = { /*istanbul ignore start*/ /*istanbul ignore end*/diff: function diff(oldString, newString) { /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0, i.e. the content starts with the same values var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { var basePath = /*istanbul ignore start*/void 0; var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { basePath = clonePath(removePath); self.pushComponent(basePath.components, undefined, true); } else { basePath = addPath; // No need to clone, we've pulled it from the list basePath.newPos++; self.pushComponent(basePath.components, true, undefined); } _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced. if (callback) { (function exec() { setTimeout(function () { // This should not happen, but we want to be safe. /* istanbul ignore next */ if (editLength > maxEditLength) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength) { var ret = execEditLength(); if (ret) { return ret; } } } }, /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) { var last = components[components.length - 1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; } else { components.push({ count: 1, added: added, removed: removed }); } }, /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.components.push({ count: commonCount }); } basePath.newPos = newPos; return oldPos; }, /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) { return left === right; }, /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) { return value; }, /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) { return value.split(''); }, /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) { return chars.join(''); } }; function buildValues(diff, components, newString, oldString, useLongestToken) { var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored. For this case we merge the // terminal into the prior string and drop the change. var lastComponent = components[componentLen - 1]; if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { components[componentLen - 2].value += lastComponent.value; components.pop(); } return components; } function clonePath(path$$1) { return { newPos: path$$1.newPos, components: path$$1.components.slice(0) }; } }); unwrapExports(base); var character = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.characterDiff = undefined; exports. /*istanbul ignore end*/diffChars = diffChars; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default'](); function diffChars(oldStr, newStr, callback) { return characterDiff.diff(oldStr, newStr, callback); } }); unwrapExports(character); var params = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/generateOptions = generateOptions; function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } }); unwrapExports(params); var word$1 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.wordDiff = undefined; exports. /*istanbul ignore end*/diffWords = diffWords; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ &#711; Caron // - U+02D8 ˘ &#728; Breve // - U+02D9 ˙ &#729; Dot Above // - U+02DA ˚ &#730; Ring Above // - U+02DB ˛ &#731; Ogonek // - U+02DC ˜ &#732; Small Tilde // - U+02DD ˝ &#733; Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default'](); wordDiff.equals = function (left, right) { return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { var tokens = value.split(/(\s+|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, callback) { var options = /*istanbul ignore start*/(0, params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, callback) { return wordDiff.diff(oldStr, newStr, callback); } }); unwrapExports(word$1); var line$7 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.lineDiff = undefined; exports. /*istanbul ignore end*/diffLines = diffLines; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default'](); lineDiff.tokenize = function (value) { var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = /*istanbul ignore start*/(0, params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } }); unwrapExports(line$7); var sentence = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.sentenceDiff = undefined; exports. /*istanbul ignore end*/diffSentences = diffSentences; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'](); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } }); unwrapExports(sentence); var css = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.cssDiff = undefined; exports. /*istanbul ignore end*/diffCss = diffCss; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default'](); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } }); unwrapExports(css); var json$1 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.jsonDiff = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports. /*istanbul ignore end*/diffJson = diffJson; /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/ var objectPrototypeToString = Object.prototype.toString; var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default'](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = /*istanbul ignore start*/line$7.lineDiff. /*istanbul ignore end*/tokenize; jsonDiff.castInput = function (value) { /*istanbul ignore start*/var /*istanbul ignore end*/undefinedReplacement = this.options.undefinedReplacement; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function (k, v) { if (typeof v === 'undefined') { return undefinedReplacement; } return v; }, ' '); }; jsonDiff.equals = function (left, right) { return (/*istanbul ignore start*/_base2['default']. /*istanbul ignore end*/prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) ); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. function canonicalize(obj, stack, replacementStack) { stack = stack || []; replacementStack = replacementStack || []; var i = /*istanbul ignore start*/void 0; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj = /*istanbul ignore start*/void 0; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], key = /*istanbul ignore start*/void 0; for (key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(key)) { sortedKeys.push(key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { key = sortedKeys[i]; canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } }); unwrapExports(json$1); var array$1 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.arrayDiff = undefined; exports. /*istanbul ignore end*/diffArrays = diffArrays; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default'](); arrayDiff.tokenize = arrayDiff.join = function (value) { return value.slice(); }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } }); unwrapExports(array$1); var parse$10 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/parsePatch = parsePatch; function parsePatch(uniDiff) { /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var headerPattern = /^(---|\+\+\+)\s+([\S ]*)(?:\t(.*?)\s*)?$/; var fileHeader = headerPattern.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; index[keyPrefix + 'FileName'] = fileHeader[2]; index[keyPrefix + 'Header'] = fileHeader[3]; i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: +chunkHeader[2] || 1, newStart: +chunkHeader[3], newLines: +chunkHeader[4] || 1, lines: [], linedelimiters: [] }; var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } }); unwrapExports(parse$10); var distanceIterator = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/"use strict"; exports.__esModule = true; exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text lenght, then // hunk can't fit on the text. Return undefined }; }; }); unwrapExports(distanceIterator); var apply = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/applyPatch = applyPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPatches; /*istanbul ignore start*/ var _distanceIterator2 = _interopRequireDefault(distanceIterator); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/function applyPatch(source, uniDiff) { /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/(0, parse$10.parsePatch) /*istanbul ignore end*/(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{ return (/*istanbul ignore end*/line === patchContent ); }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, addEOFNL = /*istanbul ignore start*/void 0; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line[0], content = line.substr(1); if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) /*istanbul ignore end*/(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.offset + _hunk.newStart - 1; if (_hunk.newLines == 0) { _toPos++; } for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line[0], content = line.substr(1), delimiter = _hunk.linedelimiters[j]; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/(0, parse$10.parsePatch) /*istanbul ignore end*/(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } }); unwrapExports(apply); var create = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/structuredPatch = structuredPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = createTwoFilesPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPatch; /*istanbul ignore start*/ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = /*istanbul ignore start*/(0, line$7.diffLines) /*istanbul ignore end*/(oldStr, newStr, options); diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; /*istanbul ignore start*/ var _loop = function _loop( /*istanbul ignore end*/i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { /*istanbul ignore start*/ var _curRange; /*istanbul ignore end*/ // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { /*istanbul ignore start*/ var _curRange2; /*istanbul ignore end*/ // Overlapping /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines))); } else { /*istanbul ignore start*/ var _curRange3; /*istanbul ignore end*/ // end the range and output var contextSize = Math.min(lines.length, options.context); /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); if (lines.length == 0 && !oldEOFNewline) { // special case: old has no eol and no trailing context; no-nl can end up before adds curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } else if (!oldEOFNewline || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { /*istanbul ignore start*/ _loop( /*istanbul ignore end*/i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); var ret = []; if (oldFileName == newFileName) { ret.push('Index: ' + oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } }); unwrapExports(create); var dmp = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/"use strict"; exports.__esModule = true; exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP; // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, operation = /*istanbul ignore start*/void 0; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } }); unwrapExports(dmp); var xml = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML; function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push('<ins>'); } else if (change.removed) { ret.push('<del>'); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push('</ins>'); } else if (change.removed) { ret.push('</del>'); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&amp;'); n = n.replace(/</g, '&lt;'); n = n.replace(/>/g, '&gt;'); n = n.replace(/"/g, '&quot;'); return n; } }); unwrapExports(xml); var lib$5 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined; /*istanbul ignore end*/ /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports. /*istanbul ignore end*/Diff = _base2['default']; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = character.diffChars; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = word$1.diffWords; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = word$1.diffWordsWithSpace; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = line$7.diffLines; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = line$7.diffTrimmedLines; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = sentence.diffSentences; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = css.diffCss; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = json$1.diffJson; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = array$1.diffArrays; /*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = create.structuredPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = create.createTwoFilesPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = create.createPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = apply.applyPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = apply.applyPatches; /*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = parse$10.parsePatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = dmp.convertChangesToDMP; /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = xml.convertChangesToXML; /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = json$1.canonicalize; /* See LICENSE file for terms of use */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ }); unwrapExports(lib$5); const cleanAST = cleanAst.cleanAST; const getSupportInfo$3 = support.getSupportInfo; const OPTION_USAGE_THRESHOLD = 25; const CHOICE_USAGE_MARGIN = 3; const CHOICE_USAGE_INDENTATION = 2; function getOptions(argv, detailedOptions) { return detailedOptions.filter(option => option.forwardToApi).reduce( (current, option) => Object.assign(current, { [option.forwardToApi]: argv[option.name] }), {} ); } function cliifyOptions(object, apiDetailedOptionMap) { return Object.keys(object || {}).reduce((output, key) => { const apiOption = apiDetailedOptionMap[key]; const cliKey = apiOption ? apiOption.name : key; output[dashify(cliKey)] = object[key]; return output; }, {}); } function diff(a, b) { return lib$5.createTwoFilesPatch("", "", a, b, "", "", { context: 2 }); } function handleError(context, filename, error) { const isParseError = Boolean(error && error.loc); const isValidationError = /Validation Error/.test(error && error.message); // For parse errors and validation errors, we only want to show the error // message formatted in a nice way. `String(error)` takes care of that. Other // (unexpected) errors are passed as-is as a separate argument to // `console.error`. That includes the stack trace (if any), and shows a nice // `util.inspect` of throws things that aren't `Error` objects. (The Flow // parser has mistakenly thrown arrays sometimes.) if (isParseError) { context.logger.error(`${filename}: ${String(error)}`); } else if (isValidationError || error instanceof errors.ConfigError) { context.logger.error(String(error)); // If validation fails for one file, it will fail for all of them. process.exit(1); } else if (error instanceof errors.DebugError) { context.logger.error(`${filename}: ${error.message}`); } else { context.logger.error(filename + ": " + (error.stack || error)); } // Don't exit the process if one file failed process.exitCode = 2; } function logResolvedConfigPathOrDie(context, filePath) { const configFile = resolveConfig_1.resolveConfigFile.sync(filePath); if (configFile) { context.logger.log(path.relative(process.cwd(), configFile)); } else { process.exit(1); } } function writeOutput(result, options) { // Don't use `console.log` here since it adds an extra newline at the end. process.stdout.write(result.formatted); if (options.cursorOffset >= 0) { process.stderr.write(result.cursorOffset + "\n"); } } function listDifferent(context, input, options, filename) { if (!context.argv["list-different"]) { return; } options = Object.assign({}, options, { filepath: filename }); if (!prettier$2.check(input, options)) { if (!context.argv["write"]) { context.logger.log(filename); } process.exitCode = 1; } return true; } function format$1(context, input, opt) { if (context.argv["debug-print-doc"]) { const doc = prettier$2.__debug.printToDoc(input, opt); return { formatted: prettier$2.__debug.formatDoc(doc) }; } if (context.argv["debug-check"]) { const pp = prettier$2.format(input, opt); const pppp = prettier$2.format(pp, opt); if (pp !== pppp) { throw new errors.DebugError( "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp) ); } else { const normalizedOpts = options$12.normalize(opt); const ast = cleanAST( prettier$2.__debug.parse(input, opt).ast, normalizedOpts ); const past = cleanAST( prettier$2.__debug.parse(pp, opt).ast, normalizedOpts ); if (ast !== past) { const MAX_AST_SIZE = 2097152; // 2MB const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past); throw new errors.DebugError( "ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp) ); } } return { formatted: opt.filepath || "(stdin)\n" }; } return prettier$2.formatWithCursor(input, opt); } function getOptionsOrDie(context, filePath) { try { if (context.argv["config"] === false) { context.logger.debug( "'--no-config' option found, skip loading config file." ); return null; } context.logger.debug( context.argv["config"] ? `load config file from '${context.argv["config"]}'` : `resolve config from '${filePath}'` ); const options = resolveConfig_1.resolveConfig.sync(filePath, { editorconfig: context.argv["editorconfig"], config: context.argv["config"] }); context.logger.debug("loaded options `" + JSON.stringify(options) + "`"); return options; } catch (error) { context.logger.error("Invalid configuration file: " + error.message); process.exit(2); } } function getOptionsForFile(context, filepath) { const options = getOptionsOrDie(context, filepath); const hasPlugins = options && options.plugins; if (hasPlugins) { pushContextPlugins(context, options.plugins); } const appliedOptions = Object.assign( { filepath }, applyConfigPrecedence( context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, { logger: context.logger }) ) ); context.logger.debug( `applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}` ); if (hasPlugins) { popContextPlugins(context); } return appliedOptions; } function parseArgsToOptions(context, overrideDefaults) { const minimistOptions = createMinimistOptions(context.detailedOptions); const apiDetailedOptionMap = createApiDetailedOptionMap( context.detailedOptions ); return getOptions( optionsNormalizer.normalizeCliOptions( minimist_1( context.args, Object.assign({ string: minimistOptions.string, boolean: minimistOptions.boolean, default: cliifyOptions(overrideDefaults, apiDetailedOptionMap) }) ), context.detailedOptions, { logger: false } ), context.detailedOptions ); } function applyConfigPrecedence(context, options) { try { switch (context.argv["config-precedence"]) { case "cli-override": return parseArgsToOptions(context, options); case "file-override": return Object.assign({}, parseArgsToOptions(context), options); case "prefer-file": return options || parseArgsToOptions(context); } } catch (error) { context.logger.error(error.toString()); process.exit(2); } } function formatStdin(context) { const filepath = context.argv["stdin-filepath"] ? path.resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd(); const ignorer = createIgnorer(context); const relativeFilepath = path.relative(process.cwd(), filepath); thirdParty$1.getStream(process.stdin).then(input => { if (relativeFilepath && ignorer.filter([relativeFilepath]).length === 0) { writeOutput({ formatted: input }, {}); return; } const options = getOptionsForFile(context, filepath); if (listDifferent(context, input, options, "(stdin)")) { return; } try { writeOutput(format$1(context, input, options), options); } catch (error) { handleError(context, "stdin", error); } }); } function createIgnorer(context) { const ignoreFilePath = path.resolve(context.argv["ignore-path"]); let ignoreText = ""; try { ignoreText = fs.readFileSync(ignoreFilePath, "utf8"); } catch (readError) { if (readError.code !== "ENOENT") { context.logger.error( `Unable to read ${ignoreFilePath}: ` + readError.message ); process.exit(2); } } return ignore().add(ignoreText); } function eachFilename(context, patterns, callback) { const ignoreNodeModules = context.argv["with-node-modules"] !== true; if (ignoreNodeModules) { patterns = patterns.concat(["!**/node_modules/**", "!./node_modules/**"]); } try { const filePaths = globby .sync(patterns, { dot: true, nodir: true }) .map(filePath => path.relative(process.cwd(), filePath)); if (filePaths.length === 0) { context.logger.error( `No matching files. Patterns tried: ${patterns.join(" ")}` ); process.exitCode = 2; return; } filePaths.forEach(filePath => callback(filePath, getOptionsForFile(context, filePath)) ); } catch (error) { context.logger.error( `Unable to expand glob patterns: ${patterns.join(" ")}\n${error.message}` ); // Don't exit the process if one pattern failed process.exitCode = 2; } } function formatFiles(context) { // The ignorer will be used to filter file paths after the glob is checked, // before any files are actually written const ignorer = createIgnorer(context); eachFilename(context, context.filePatterns, (filename, options) => { const fileIgnored = ignorer.filter([filename]).length === 0; if ( fileIgnored && (context.argv["write"] || context.argv["list-different"]) ) { return; } if (context.argv["write"] && process.stdout.isTTY) { // Don't use `console.log` here since we need to replace this line. context.logger.log(filename, { newline: false }); } let input; try { input = fs.readFileSync(filename, "utf8"); } catch (error) { // Add newline to split errors from filename line. context.logger.log(""); context.logger.error( `Unable to read file: ${filename}\n${error.message}` ); // Don't exit the process if one file failed process.exitCode = 2; return; } if (fileIgnored) { writeOutput({ formatted: input }, options); return; } listDifferent(context, input, options, filename); const start = Date.now(); let result; let output; try { result = format$1( context, input, Object.assign({}, options, { filepath: filename }) ); output = result.formatted; } catch (error) { // Add newline to split errors from filename line. process.stdout.write("\n"); handleError(context, filename, error); return; } if (context.argv["write"]) { if (process.stdout.isTTY) { // Remove previously printed filename to log it with duration. readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0, null); } // Don't write the file if it won't change in order not to invalidate // mtime based caches. if (output === input) { if (!context.argv["list-different"]) { context.logger.log(`${chalk$2.grey(filename)} ${Date.now() - start}ms`); } } else { if (context.argv["list-different"]) { context.logger.log(filename); } else { context.logger.log(`${filename} ${Date.now() - start}ms`); } try { fs.writeFileSync(filename, output, "utf8"); } catch (error) { context.logger.error( `Unable to write file: ${filename}\n${error.message}` ); // Don't exit the process if one file failed process.exitCode = 2; } } } else if (context.argv["debug-check"]) { if (output) { context.logger.log(output); } else { process.exitCode = 2; } } else if (!context.argv["list-different"]) { writeOutput(result, options); } }); } function getOptionsWithOpposites(options) { // Add --no-foo after --foo. const optionsWithOpposites = options.map(option => [ option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, { name: `no-${option.name}`, type: "boolean", description: option.oppositeDescription }) : null ]); return flattenArray(optionsWithOpposites).filter(Boolean); } function createUsage(context) { const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag> option => !( option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-") ) ); const groupedOptions = groupBy(options, option => option.category); const firstCategories = constant.categoryOrder.slice(0, -1); const lastCategories = constant.categoryOrder.slice(-1); const restCategories = Object.keys(groupedOptions).filter( category => firstCategories.indexOf(category) === -1 && lastCategories.indexOf(category) === -1 ); const allCategories = firstCategories.concat(restCategories, lastCategories); const optionsUsage = allCategories.map(category => { const categoryOptions = groupedOptions[category] .map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)) .join("\n"); return `${category} options:\n\n${indent$9(categoryOptions, 2)}`; }); return [constant.usageSummary].concat(optionsUsage, [""]).join("\n\n"); } function createOptionUsage(context, option, threshold) { const header = createOptionUsageHeader(option); const optionDefaultValue = getOptionDefaultValue(context, option.name); return createOptionUsageRow( header, `${option.description}${ optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.` }`, threshold ); } function createDefaultValueDisplay(value) { return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value; } function createOptionUsageHeader(option) { const name = `--${option.name}`; const alias = option.alias ? `-${option.alias},` : null; const type = createOptionUsageType(option); return [alias, name, type].filter(Boolean).join(" "); } function createOptionUsageRow(header, content, threshold) { const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length); const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`); return `${header}${separator}${description}`; } function createOptionUsageType(option) { switch (option.type) { case "boolean": return null; case "choice": return `<${option.choices .filter(choice => !choice.deprecated) .map(choice => choice.value) .join("|")}>`; default: return `<${option.type}>`; } } function flattenArray(array) { return [].concat.apply([], array); } function getOptionWithLevenSuggestion(context, options, optionName) { // support aliases const optionNameContainers = flattenArray( options.map((option, index) => [ { value: option.name, index }, option.alias ? { value: option.alias, index } : null ]) ).filter(Boolean); const optionNameContainer = optionNameContainers.find( optionNameContainer => optionNameContainer.value === optionName ); if (optionNameContainer !== undefined) { return options[optionNameContainer.index]; } const suggestedOptionNameContainer = optionNameContainers.find( optionNameContainer => leven(optionNameContainer.value, optionName) < 3 ); if (suggestedOptionNameContainer !== undefined) { const suggestedOptionName = suggestedOptionNameContainer.value; context.logger.warn( `Unknown option name "${optionName}", did you mean "${suggestedOptionName}"?` ); return options[suggestedOptionNameContainer.index]; } context.logger.warn(`Unknown option name "${optionName}"`); return options.find(option => option.name === "help"); } function createChoiceUsages(choices, margin, indentation) { const activeChoices = choices.filter(choice => !choice.deprecated); const threshold = activeChoices .map(choice => choice.value.length) .reduce((current, length) => Math.max(current, length), 0) + margin; return activeChoices.map(choice => indent$9( createOptionUsageRow(choice.value, choice.description, threshold), indentation ) ); } function createDetailedUsage(context, optionName) { const option = getOptionWithLevenSuggestion( context, getOptionsWithOpposites(context.detailedOptions), optionName ); const header = createOptionUsageHeader(option); const description = `\n\n${indent$9(option.description, 2)}`; const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages( option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION ).join("\n")}`; const optionDefaultValue = getOptionDefaultValue(context, option.name); const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : ""; const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map( key => `\n* ${key}: ${createDefaultValueDisplay( option.pluginDefaults[key] )}` )}` : ""; return `${header}${description}${choices}${defaults}${pluginDefaults}`; } function getOptionDefaultValue(context, optionName) { // --no-option if (!(optionName in context.detailedOptionMap)) { return undefined; } const option = context.detailedOptionMap[optionName]; if (option.default !== undefined) { return option.default; } const optionCamelName = camelcase(optionName); if (optionCamelName in context.apiDefaultOptions) { return context.apiDefaultOptions[optionCamelName]; } return undefined; } function indent$9(str, spaces) { return str.replace(/^/gm, " ".repeat(spaces)); } function groupBy(array, getKey) { return array.reduce((obj, item) => { const key = getKey(item); const previousItems = key in obj ? obj[key] : []; return Object.assign({}, obj, { [key]: previousItems.concat(item) }); }, Object.create(null)); } function pick(object, keys) { return !keys ? object : keys.reduce( (reduced, key) => Object.assign(reduced, { [key]: object[key] }), {} ); } function createLogger(logLevel) { return { warn: createLogFunc("warn", "yellow"), error: createLogFunc("error", "red"), debug: createLogFunc("debug", "blue"), log: createLogFunc("log") }; function createLogFunc(loggerName, color) { if (!shouldLog(loggerName)) { return () => {}; } const prefix = color ? `[${chalk$2[color](loggerName)}] ` : ""; return function(message, opts) { opts = Object.assign({ newline: true }, opts); const stream = process[loggerName === "log" ? "stdout" : "stderr"]; stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : "")); }; } function shouldLog(loggerName) { switch (logLevel) { case "silent": return false; default: return true; case "debug": if (loggerName === "debug") { return true; } // fall through case "log": if (loggerName === "log") { return true; } // fall through case "warn": if (loggerName === "warn") { return true; } // fall through case "error": return loggerName === "error"; } } } function normalizeDetailedOption(name, option) { return Object.assign({ category: constant.CATEGORY_OTHER }, option, { choices: option.choices && option.choices.map(choice => { const newChoice = Object.assign( { description: "", deprecated: false }, typeof choice === "object" ? choice : { value: choice } ); if (newChoice.value === true) { newChoice.value = ""; // backward compability for original boolean option } return newChoice; }) }); } function normalizeDetailedOptionMap(detailedOptionMap) { return Object.keys(detailedOptionMap) .sort() .reduce((normalized, name) => { const option = detailedOptionMap[name]; return Object.assign(normalized, { [name]: normalizeDetailedOption(name, option) }); }, {}); } function createMinimistOptions(detailedOptions) { return { boolean: detailedOptions .filter(option => option.type === "boolean") .map(option => option.name), string: detailedOptions .filter(option => option.type !== "boolean") .map(option => option.name), default: detailedOptions .filter(option => !option.deprecated) .filter(option => !option.forwardToApi || option.name === "plugin") .filter(option => option.default !== undefined) .reduce( (current, option) => Object.assign({ [option.name]: option.default }, current), {} ), alias: detailedOptions .filter(option => option.alias !== undefined) .reduce( (current, option) => Object.assign({ [option.name]: option.alias }, current), {} ) }; } function createApiDetailedOptionMap(detailedOptions) { return detailedOptions.reduce( (current, option) => option.forwardToApi && option.forwardToApi !== option.name ? Object.assign(current, { [option.forwardToApi]: option }) : current, {} ); } function createDetailedOptionMap(supportOptions) { return supportOptions.reduce((reduced, option) => { const newOption = Object.assign({}, option, { name: option.cliName || dashify(option.name), description: option.cliDescription || option.description, category: option.cliCategory || constant.CATEGORY_FORMAT, forwardToApi: option.name }); if (option.deprecated) { delete newOption.forwardToApi; delete newOption.description; delete newOption.oppositeDescription; newOption.deprecated = true; } return Object.assign(reduced, { [newOption.name]: newOption }); }, {}); } //-----------------------------context-util-start------------------------------- /** * @typedef {Object} Context * @property logger * @property args * @property argv * @property filePatterns * @property supportOptions * @property detailedOptions * @property detailedOptionMap * @property apiDefaultOptions */ function createContext(args) { const context = { args }; updateContextArgv(context); normalizeContextArgv(context, ["loglevel", "plugin"]); context.logger = createLogger(context.argv["loglevel"]); updateContextArgv(context, context.argv["plugin"]); return context; } function initContext(context) { // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js normalizeContextArgv(context); } function updateContextOptions(context, plugins) { const supportOptions = getSupportInfo$3(null, { showDeprecated: true, showUnreleased: true, showInternal: true, plugins }).options; const detailedOptionMap = normalizeDetailedOptionMap( Object.assign({}, createDetailedOptionMap(supportOptions), constant.options) ); const detailedOptions = util$1.arrayify(detailedOptionMap, "name"); const apiDefaultOptions = supportOptions .filter(optionInfo => !optionInfo.deprecated) .reduce( (reduced, optionInfo) => Object.assign(reduced, { [optionInfo.name]: optionInfo.default }), Object.assign({}, options$12.hiddenDefaults) ); context.supportOptions = supportOptions; context.detailedOptions = detailedOptions; context.detailedOptionMap = detailedOptionMap; context.apiDefaultOptions = apiDefaultOptions; } function pushContextPlugins(context, plugins) { context._supportOptions = context.supportOptions; context._detailedOptions = context.detailedOptions; context._detailedOptionMap = context.detailedOptionMap; context._apiDefaultOptions = context.apiDefaultOptions; updateContextOptions(context, plugins); } function popContextPlugins(context) { context.supportOptions = context._supportOptions; context.detailedOptions = context._detailedOptions; context.detailedOptionMap = context._detailedOptionMap; context.apiDefaultOptions = context._apiDefaultOptions; } function updateContextArgv(context, plugins) { pushContextPlugins(context, plugins); const minimistOptions = createMinimistOptions(context.detailedOptions); const argv = minimist_1(context.args, minimistOptions); context.argv = argv; context.filePatterns = argv["_"]; } function normalizeContextArgv(context, keys) { const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter( option => keys.indexOf(option.name) !== -1 ); const argv = !keys ? context.argv : pick(context.argv, keys); context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, { logger: context.logger }); } //------------------------------context-util-end-------------------------------- var util_1 = { createContext, createDetailedOptionMap, createDetailedUsage, createUsage, format: format$1, formatFiles, formatStdin, initContext, logResolvedConfigPathOrDie, normalizeDetailedOptionMap }; function run(args) { const context = util_1.createContext(args); try { util_1.initContext(context); context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`); if (context.argv["write"] && context.argv["debug-check"]) { context.logger.error("Cannot use --write and --debug-check together."); process.exit(1); } if (context.argv["find-config-path"] && context.filePatterns.length) { context.logger.error("Cannot use --find-config-path with multiple files"); process.exit(1); } if (context.argv["version"]) { context.logger.log(prettier$2.version); process.exit(0); } if (context.argv["help"] !== undefined) { context.logger.log( typeof context.argv["help"] === "string" && context.argv["help"] !== "" ? util_1.createDetailedUsage(context, context.argv["help"]) : util_1.createUsage(context) ); process.exit(0); } if (context.argv["support-info"]) { context.logger.log( prettier$2.format(jsonStableStringify(prettier$2.getSupportInfo()), { parser: "json" }) ); process.exit(0); } const hasFilePatterns = context.filePatterns.length !== 0; const useStdin = context.argv["stdin"] || (!hasFilePatterns && !process.stdin.isTTY); if (context.argv["find-config-path"]) { util_1.logResolvedConfigPathOrDie( context, context.argv["find-config-path"] ); } else if (useStdin) { util_1.formatStdin(context); } else if (hasFilePatterns) { util_1.formatFiles(context); } else { context.logger.log(util_1.createUsage(context)); process.exit(1); } } catch (error) { context.logger.error(error.message); process.exit(1); } } var cli = { run }; cli.run(process.argv.slice(2)); var prettier = { }; module.exports = prettier; Kodo/kodo - Gogs: Go Git Service

1 Commits (26bef94de6d9320e27ab30bb8def0d68a35012d4)

Author SHA1 Message Date
  huangqimin 3d0d214667 :sparkles: Member Infos 6 years ago