!nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
// string literal with newlines
var _shouldBreak = _n.attributes && _n.attributes.some(function (attr) {
return attr.value && isStringLiteral(attr.value) && attr.value.value.includes("\n");
});
return group$1(concat$4(["<", path$$1.call(print, "name"), path$$1.call(print, "typeParameters"), concat$4([indent$2(concat$4(path$$1.map(function (attr) {
return concat$4([line$3, print(attr)]);
}, "attributes"))), _n.selfClosing ? line$3 : bracketSameLine ? ">" : softline$1]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
shouldBreak: _shouldBreak
});
}
case "JSXClosingElement":
return concat$4(["", path$$1.call(print, "name"), ">"]);
case "JSXOpeningFragment":
case "JSXClosingFragment":
case "TSJsxOpeningFragment":
case "TSJsxClosingFragment":
{
var hasComment = n.comments && n.comments.length;
var hasOwnLineComment = hasComment && !n.comments.every(comments$3.isBlockComment);
var isOpeningFragment = n.type === "JSXOpeningFragment" || n.type === "TSJsxOpeningFragment";
return concat$4([isOpeningFragment ? "<" : "", indent$2(concat$4([hasOwnLineComment ? hardline$3 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path$$1, options, true)])), hasOwnLineComment ? hardline$3 : "", ">"]);
}
case "JSXText":
/* istanbul ignore next */
throw new Error("JSXTest should be handled by JSXElement");
case "JSXEmptyExpression":
{
var requiresHardline = n.comments && !n.comments.every(comments$3.isBlockComment);
return concat$4([comments.printDanglingComments(path$$1, options,
/* sameIndent */
!requiresHardline), requiresHardline ? hardline$3 : ""]);
}
case "ClassBody":
if (!n.comments && n.body.length === 0) {
return "{}";
}
return concat$4(["{", n.body.length > 0 ? indent$2(concat$4([hardline$3, path$$1.call(function (bodyPath) {
return printStatementSequence(bodyPath, options, print);
}, "body")])) : comments.printDanglingComments(path$$1, options), hardline$3, "}"]);
case "ClassProperty":
case "TSAbstractClassProperty":
case "ClassPrivateProperty":
{
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.static) {
parts.push("static ");
}
if (n.type === "TSAbstractClassProperty") {
parts.push("abstract ");
}
if (n.readonly) {
parts.push("readonly ");
}
var variance = getFlowVariance(n);
if (variance) {
parts.push(variance);
}
if (n.computed) {
parts.push("[", path$$1.call(print, "key"), "]");
} else {
parts.push(printPropertyKey(path$$1, options, print));
}
parts.push(printTypeAnnotation(path$$1, options, print));
if (n.value) {
parts.push(" =", printAssignmentRight(n.key, n.value, path$$1.call(print, "value"), options));
}
parts.push(semi);
return group$1(concat$4(parts));
}
case "ClassDeclaration":
case "ClassExpression":
case "TSAbstractClassDeclaration":
if (isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
parts.push(concat$4(printClass(path$$1, options, print)));
return concat$4(parts);
case "TSInterfaceHeritage":
parts.push(path$$1.call(print, "id"));
if (n.typeParameters) {
parts.push(path$$1.call(print, "typeParameters"));
}
return concat$4(parts);
case "TemplateElement":
return join$2(literalline$1, n.value.raw.split(/\r?\n/g));
case "TemplateLiteral":
{
var expressions = path$$1.map(print, "expressions");
var _parentNode = path$$1.getParentNode();
/**
* describe.each`table`(name, fn)
* describe.only.each`table`(name, fn)
* describe.skip.each`table`(name, fn)
* test.each`table`(name, fn)
* test.only.each`table`(name, fn)
* test.skip.each`table`(name, fn)
*
* Ref: https://github.com/facebook/jest/pull/6102
*/
var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
if (_parentNode.type === "TaggedTemplateExpression" && _parentNode.quasi === n && _parentNode.tag.type === "MemberExpression" && _parentNode.tag.property.type === "Identifier" && _parentNode.tag.property.name === "each" && (_parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(_parentNode.tag.object.name) || _parentNode.tag.object.type === "MemberExpression" && _parentNode.tag.object.property.type === "Identifier" && (_parentNode.tag.object.property.name === "only" || _parentNode.tag.object.property.name === "skip") && _parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(_parentNode.tag.object.object.name))) {
/**
* a | b | expected
* ${1} | ${1} | ${2}
* ${1} | ${2} | ${3}
* ${2} | ${1} | ${3}
*/
var headerNames = n.quasis[0].value.raw.trim().split(/\s*\|\s*/);
if (headerNames.length > 1 || headerNames.some(function (headerName) {
return headerName.length !== 0;
})) {
var stringifiedExpressions = expressions.map(function (doc$$2) {
return "${" + printDocToString$2(doc$$2, Object.assign({}, options, {
printWidth: Infinity
})).formatted + "}";
});
var tableBody = [{
hasLineBreak: false,
cells: []
}];
for (var _i = 1; _i < n.quasis.length; _i++) {
var row = tableBody[tableBody.length - 1];
var correspondingExpression = stringifiedExpressions[_i - 1];
row.cells.push(correspondingExpression);
if (correspondingExpression.indexOf("\n") !== -1) {
row.hasLineBreak = true;
}
if (n.quasis[_i].value.raw.indexOf("\n") !== -1) {
tableBody.push({
hasLineBreak: false,
cells: []
});
}
}
var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) {
return Math.max(maxColumnCount, row.cells.length);
}, headerNames.length);
var maxColumnWidths = Array.from(new Array(maxColumnCount), function () {
return 0;
});
var table = [{
cells: headerNames
}].concat(tableBody.filter(function (row) {
return row.cells.length !== 0;
}));
table.filter(function (row) {
return !row.hasLineBreak;
}).forEach(function (row) {
row.cells.forEach(function (cell, index) {
maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$1(cell));
});
});
parts.push("`", indent$2(concat$4([hardline$3, join$2(hardline$3, table.map(function (row) {
return join$2(" | ", row.cells.map(function (cell, index) {
return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$1(cell));
}));
}))])), hardline$3, "`");
return concat$4(parts);
}
}
parts.push("`");
path$$1.each(function (childPath) {
var i = childPath.getName();
parts.push(print(childPath));
if (i < expressions.length) {
// For a template literal of the following form:
// `someQuery {
// ${call({
// a,
// b,
// })}
// }`
// the expression is on its own line (there is a \n in the previous
// quasi literal), therefore we want to indent the JavaScript
// expression inside at the beginning of ${ instead of the beginning
// of the `.
var tabWidth = options.tabWidth;
var indentSize = getIndentSize$1(childPath.getValue().value.raw, tabWidth);
var _printed = expressions[i];
if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression") {
_printed = concat$4([indent$2(concat$4([softline$1, _printed])), softline$1]);
}
var aligned = addAlignmentToDoc$2(_printed, indentSize, tabWidth);
parts.push(group$1(concat$4(["${", aligned, lineSuffixBoundary$1, "}"])));
}
}, "quasis");
parts.push("`");
return concat$4(parts);
}
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
case "TaggedTemplateExpression":
return concat$4([path$$1.call(print, "tag"), path$$1.call(print, "typeParameters"), path$$1.call(print, "quasi")]);
case "Node":
case "Printable":
case "SourceLocation":
case "Position":
case "Statement":
case "Function":
case "Pattern":
case "Expression":
case "Declaration":
case "Specifier":
case "NamedSpecifier":
case "Comment":
case "MemberTypeAnnotation": // Flow
case "Type":
/* istanbul ignore next */
throw new Error("unprintable type: " + JSON.stringify(n.type));
// Type Annotations for Facebook Flow, typically stripped out or
// transformed away before printing.
case "TypeAnnotation":
case "TSTypeAnnotation":
if (n.typeAnnotation) {
return path$$1.call(print, "typeAnnotation");
}
/* istanbul ignore next */
return "";
case "TSTupleType":
case "TupleTypeAnnotation":
{
var typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
return group$1(concat$4(["[", indent$2(concat$4([softline$1, printArrayItems(path$$1, options, typesField, print)])), // TypeScript doesn't support trailing commas in tuple types
n.type === "TSTupleType" ? "" : ifBreak$1(shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path$$1, options,
/* sameIndent */
true), softline$1, "]"]));
}
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
return "empty";
case "AnyTypeAnnotation":
return "any";
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return concat$4([path$$1.call(print, "elementType"), "[]"]);
case "BooleanTypeAnnotation":
return "boolean";
case "BooleanLiteralTypeAnnotation":
return "" + n.value;
case "DeclareClass":
return printFlowDeclaration(path$$1, printClass(path$$1, options, print));
case "DeclareFunction":
// For TypeScript the DeclareFunction node shares the AST
// structure with FunctionDeclaration
if (n.params) {
return concat$4(["declare ", printFunctionDeclaration(path$$1, print, options), semi]);
}
return printFlowDeclaration(path$$1, ["function ", path$$1.call(print, "id"), n.predicate ? " " : "", path$$1.call(print, "predicate"), semi]);
case "DeclareModule":
return printFlowDeclaration(path$$1, ["module ", path$$1.call(print, "id"), " ", path$$1.call(print, "body")]);
case "DeclareModuleExports":
return printFlowDeclaration(path$$1, ["module.exports", ": ", path$$1.call(print, "typeAnnotation"), semi]);
case "DeclareVariable":
return printFlowDeclaration(path$$1, ["var ", path$$1.call(print, "id"), semi]);
case "DeclareExportAllDeclaration":
return concat$4(["declare export * from ", path$$1.call(print, "source")]);
case "DeclareExportDeclaration":
return concat$4(["declare ", printExportDeclaration(path$$1, options, print)]);
case "DeclareOpaqueType":
case "OpaqueType":
{
parts.push("opaque type ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"));
if (n.supertype) {
parts.push(": ", path$$1.call(print, "supertype"));
}
if (n.impltype) {
parts.push(" = ", path$$1.call(print, "impltype"));
}
parts.push(semi);
if (n.type === "DeclareOpaqueType") {
return printFlowDeclaration(path$$1, parts);
}
return concat$4(parts);
}
case "FunctionTypeAnnotation":
case "TSFunctionType":
{
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
// var A: (a: B) => void;
var _parent6 = path$$1.getParentNode(0);
var _parentParent2 = path$$1.getParentNode(1);
var _parentParentParent = path$$1.getParentNode(2);
var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !(_parent6.type === "ObjectTypeProperty" && !getFlowVariance(_parent6) && !_parent6.optional && options.locStart(_parent6) === options.locStart(n) || _parent6.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction");
var needsColon = isArrowFunctionTypeAnnotation && (_parent6.type === "TypeAnnotation" || _parent6.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
// printing ":" as part of the expression and it would put parenthesis
// around :(
var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent6.type === "TypeAnnotation" || _parent6.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
if (isObjectTypePropertyAFunction(_parent6, options)) {
isArrowFunctionTypeAnnotation = true;
needsColon = true;
}
if (needsParens) {
parts.push("(");
}
parts.push(printFunctionParams(path$$1, print, options,
/* expandArg */
false,
/* printTypeParams */
true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
// needs to be added separately.
if (n.returnType || n.predicate || n.typeAnnotation) {
parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path$$1.call(print, "returnType"), path$$1.call(print, "predicate"), path$$1.call(print, "typeAnnotation"));
}
if (needsParens) {
parts.push(")");
}
return group$1(concat$4(parts));
}
case "FunctionTypeParam":
return concat$4([path$$1.call(print, "name"), printOptionalToken(path$$1), n.name ? ": " : "", path$$1.call(print, "typeAnnotation")]);
case "GenericTypeAnnotation":
return concat$4([path$$1.call(print, "id"), path$$1.call(print, "typeParameters")]);
case "DeclareInterface":
case "InterfaceDeclaration":
case "InterfaceTypeAnnotation":
{
if (n.type === "DeclareInterface" || isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
parts.push("interface");
if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
parts.push(" ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"));
}
if (n["extends"].length > 0) {
parts.push(group$1(indent$2(concat$4([line$3, "extends ", join$2(", ", path$$1.map(print, "extends"))]))));
}
parts.push(" ", path$$1.call(print, "body"));
return group$1(concat$4(parts));
}
case "ClassImplements":
case "InterfaceExtends":
return concat$4([path$$1.call(print, "id"), path$$1.call(print, "typeParameters")]);
case "TSIntersectionType":
case "IntersectionTypeAnnotation":
{
var types = path$$1.map(print, "types");
var result = [];
var wasIndented = false;
for (var _i2 = 0; _i2 < types.length; ++_i2) {
if (_i2 === 0) {
result.push(types[_i2]);
} else if (isObjectType(n.types[_i2 - 1]) && isObjectType(n.types[_i2])) {
// If both are objects, don't indent
result.push(concat$4([" & ", wasIndented ? indent$2(types[_i2]) : types[_i2]]));
} else if (!isObjectType(n.types[_i2 - 1]) && !isObjectType(n.types[_i2])) {
// If no object is involved, go to the next line if it breaks
result.push(indent$2(concat$4([" &", line$3, types[_i2]])));
} else {
// If you go from object to non-object or vis-versa, then inline it
if (_i2 > 1) {
wasIndented = true;
}
result.push(" & ", _i2 > 1 ? indent$2(types[_i2]) : types[_i2]);
}
}
return group$1(concat$4(result));
}
case "TSUnionType":
case "UnionTypeAnnotation":
{
// single-line variation
// A | B | C
// multi-line variation
// | A
// | B
// | C
var _parent7 = path$$1.getParentNode();
var _parentParent3 = path$$1.getParentNode(1); // If there's a leading comment, the parent is doing the indentation
var shouldIndent = _parent7.type !== "TypeParameterInstantiation" && _parent7.type !== "TSTypeParameterInstantiation" && _parent7.type !== "GenericTypeAnnotation" && _parent7.type !== "TSTypeReference" && !(_parent7.type === "FunctionTypeParam" && !_parent7.name) && _parentParent3.type !== "TSTypeAssertionExpression" && !((_parent7.type === "TypeAlias" || _parent7.type === "VariableDeclarator") && hasLeadingOwnLineComment(options.originalText, n, options)); // {
// a: string
// } | null | void
// should be inlined and not be printed in the multi-line variant
var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
// | child1
// // comment
// | child2
var _printed2 = path$$1.map(function (typePath) {
var printedType = typePath.call(print);
if (!shouldHug) {
printedType = align$1(2, printedType);
}
return comments.printComments(typePath, function () {
return printedType;
}, options);
}, "types");
if (shouldHug) {
return join$2(" | ", _printed2);
}
var code = concat$4([ifBreak$1(concat$4([shouldIndent ? line$3 : "", "| "])), join$2(concat$4([line$3, "| "]), _printed2)]);
var hasParens;
if (n.type === "TSUnionType") {
var greatGrandParent = path$$1.getParentNode(2);
var greatGreatGrandParent = path$$1.getParentNode(3);
hasParens = greatGrandParent && greatGrandParent.type === "TSParenthesizedType" && greatGreatGrandParent && (greatGreatGrandParent.type === "TSUnionType" || greatGreatGrandParent.type === "TSIntersectionType");
} else {
hasParens = needsParens_1(path$$1, options);
}
if (hasParens) {
return group$1(concat$4([indent$2(code), softline$1]));
}
return group$1(shouldIndent ? indent$2(code) : code);
}
case "NullableTypeAnnotation":
return concat$4(["?", path$$1.call(print, "typeAnnotation")]);
case "TSNullKeyword":
case "NullLiteralTypeAnnotation":
return "null";
case "ThisTypeAnnotation":
return "this";
case "NumberTypeAnnotation":
return "number";
case "ObjectTypeCallProperty":
if (n.static) {
parts.push("static ");
}
parts.push(path$$1.call(print, "value"));
return concat$4(parts);
case "ObjectTypeIndexer":
{
var _variance = getFlowVariance(n);
return concat$4([_variance || "", "[", path$$1.call(print, "id"), n.id ? ": " : "", path$$1.call(print, "key"), "]: ", path$$1.call(print, "value")]);
}
case "ObjectTypeProperty":
{
var _variance2 = getFlowVariance(n);
var modifier = "";
if (n.proto) {
modifier = "proto ";
} else if (n.static) {
modifier = "static ";
}
return concat$4([modifier, isGetterOrSetter(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path$$1, options, print), printOptionalToken(path$$1), isFunctionNotation(n, options) ? "" : ": ", path$$1.call(print, "value")]);
}
case "QualifiedTypeIdentifier":
return concat$4([path$$1.call(print, "qualification"), ".", path$$1.call(print, "id")]);
case "StringLiteralTypeAnnotation":
return nodeStr(n, options);
case "NumberLiteralTypeAnnotation":
assert.strictEqual(typeof n.value, "number");
if (n.extra != null) {
return printNumber$1(n.extra.raw);
}
return printNumber$1(n.raw);
case "StringTypeAnnotation":
return "string";
case "DeclareTypeAlias":
case "TypeAlias":
{
if (n.type === "DeclareTypeAlias" || isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
var _printed3 = printAssignmentRight(n.id, n.right, path$$1.call(print, "right"), options);
parts.push("type ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"), " =", _printed3, semi);
return group$1(concat$4(parts));
}
case "TypeCastExpression":
return concat$4(["(", path$$1.call(print, "expression"), ": ", path$$1.call(print, "typeAnnotation"), ")"]);
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path$$1, options, print, "params");
case "TSTypeParameter":
case "TypeParameter":
{
var _parent8 = path$$1.getParentNode();
if (_parent8.type === "TSMappedType") {
parts.push("[", path$$1.call(print, "name"));
if (n.constraint) {
parts.push(" in ", path$$1.call(print, "constraint"));
}
parts.push("]");
return concat$4(parts);
}
var _variance3 = getFlowVariance(n);
if (_variance3) {
parts.push(_variance3);
}
parts.push(path$$1.call(print, "name"));
if (n.bound) {
parts.push(": ");
parts.push(path$$1.call(print, "bound"));
}
if (n.constraint) {
parts.push(" extends ", path$$1.call(print, "constraint"));
}
if (n["default"]) {
parts.push(" = ", path$$1.call(print, "default"));
}
return concat$4(parts);
}
case "TypeofTypeAnnotation":
return concat$4(["typeof ", path$$1.call(print, "argument")]);
case "VoidTypeAnnotation":
return "void";
case "InferredPredicate":
return "%checks";
// Unhandled types below. If encountered, nodes of these types should
// be either left alone or desugared into AST types that are fully
// supported by the pretty-printer.
case "DeclaredPredicate":
return concat$4(["%checks(", path$$1.call(print, "value"), ")"]);
case "TSAbstractKeyword":
return "abstract";
case "TSAnyKeyword":
return "any";
case "TSAsyncKeyword":
return "async";
case "TSBooleanKeyword":
return "boolean";
case "TSConstKeyword":
return "const";
case "TSDeclareKeyword":
return "declare";
case "TSExportKeyword":
return "export";
case "TSNeverKeyword":
return "never";
case "TSNumberKeyword":
return "number";
case "TSObjectKeyword":
return "object";
case "TSProtectedKeyword":
return "protected";
case "TSPrivateKeyword":
return "private";
case "TSPublicKeyword":
return "public";
case "TSReadonlyKeyword":
return "readonly";
case "TSSymbolKeyword":
return "symbol";
case "TSStaticKeyword":
return "static";
case "TSStringKeyword":
return "string";
case "TSUndefinedKeyword":
return "undefined";
case "TSVoidKeyword":
return "void";
case "TSAsExpression":
return concat$4([path$$1.call(print, "expression"), " as ", path$$1.call(print, "typeAnnotation")]);
case "TSArrayType":
return concat$4([path$$1.call(print, "elementType"), "[]"]);
case "TSPropertySignature":
{
if (n.export) {
parts.push("export ");
}
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.static) {
parts.push("static ");
}
if (n.readonly) {
parts.push("readonly ");
}
if (n.computed) {
parts.push("[");
}
parts.push(printPropertyKey(path$$1, options, print));
if (n.computed) {
parts.push("]");
}
parts.push(printOptionalToken(path$$1));
if (n.typeAnnotation) {
parts.push(": ");
parts.push(path$$1.call(print, "typeAnnotation"));
} // This isn't valid semantically, but it's in the AST so we can print it.
if (n.initializer) {
parts.push(" = ", path$$1.call(print, "initializer"));
}
return concat$4(parts);
}
case "TSParameterProperty":
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.export) {
parts.push("export ");
}
if (n.static) {
parts.push("static ");
}
if (n.readonly) {
parts.push("readonly ");
}
parts.push(path$$1.call(print, "parameter"));
return concat$4(parts);
case "TSTypeReference":
return concat$4([path$$1.call(print, "typeName"), printTypeParameters(path$$1, options, print, "typeParameters")]);
case "TSTypeQuery":
return concat$4(["typeof ", path$$1.call(print, "exprName")]);
case "TSParenthesizedType":
{
return path$$1.call(print, "typeAnnotation");
}
case "TSIndexSignature":
{
var _parent9 = path$$1.getParentNode();
return concat$4([n.export ? "export " : "", n.accessibility ? concat$4([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", path$$1.call(print, "index"), "]: ", path$$1.call(print, "typeAnnotation"), _parent9.type === "ClassBody" ? semi : ""]);
}
case "TSTypePredicate":
return concat$4([path$$1.call(print, "parameterName"), " is ", path$$1.call(print, "typeAnnotation")]);
case "TSNonNullExpression":
return concat$4([path$$1.call(print, "expression"), "!"]);
case "TSThisType":
return "this";
case "TSLastTypeNode":
// TSImportType
return concat$4([!n.isTypeOf ? "" : "typeof ", "import(", path$$1.call(print, "argument"), ")", !n.qualifier ? "" : concat$4([".", path$$1.call(print, "qualifier")]), printTypeParameters(path$$1, options, print, "typeParameters")]);
case "TSLiteralType":
return path$$1.call(print, "literal");
case "TSIndexedAccessType":
return concat$4([path$$1.call(print, "objectType"), "[", path$$1.call(print, "indexType"), "]"]);
case "TSConstructSignature":
case "TSConstructorType":
case "TSCallSignature":
{
if (n.type !== "TSCallSignature") {
parts.push("new ");
}
parts.push(group$1(printFunctionParams(path$$1, print, options,
/* expandArg */
false,
/* printTypeParams */
true)));
if (n.typeAnnotation) {
var isType = n.type === "TSConstructorType";
parts.push(isType ? " => " : ": ", path$$1.call(print, "typeAnnotation"));
}
return concat$4(parts);
}
case "TSTypeOperator":
return concat$4([n.operator, " ", path$$1.call(print, "typeAnnotation")]);
case "TSMappedType":
return group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, n.readonlyToken ? concat$4([getTypeScriptMappedTypeModifier(n.readonlyToken, "readonly"), " "]) : "", printTypeScriptModifiers(path$$1, options, print), path$$1.call(print, "typeParameter"), n.questionToken ? getTypeScriptMappedTypeModifier(n.questionToken, "?") : "", ": ", path$$1.call(print, "typeAnnotation")])), comments.printDanglingComments(path$$1, options,
/* sameIndent */
true), options.bracketSpacing ? line$3 : softline$1, "}"]));
case "TSMethodSignature":
parts.push(n.accessibility ? concat$4([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path$$1.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path$$1), printFunctionParams(path$$1, print, options,
/* expandArg */
false,
/* printTypeParams */
true));
if (n.typeAnnotation) {
parts.push(": ", path$$1.call(print, "typeAnnotation"));
}
return group$1(concat$4(parts));
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", path$$1.call(print, "name"));
if (options.semi) {
parts.push(";");
}
return group$1(concat$4(parts));
case "TSEnumDeclaration":
if (isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
if (n.modifiers) {
parts.push(printTypeScriptModifiers(path$$1, options, print));
}
if (n.const) {
parts.push("const ");
}
parts.push("enum ", path$$1.call(print, "id"), " ");
if (n.members.length === 0) {
parts.push(group$1(concat$4(["{", comments.printDanglingComments(path$$1, options), softline$1, "}"])));
} else {
parts.push(group$1(concat$4(["{", indent$2(concat$4([hardline$3, printArrayItems(path$$1, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path$$1, options,
/* sameIndent */
true), hardline$3, "}"])));
}
return concat$4(parts);
case "TSEnumMember":
parts.push(path$$1.call(print, "id"));
if (n.initializer) {
parts.push(" = ", path$$1.call(print, "initializer"));
}
return concat$4(parts);
case "TSImportEqualsDeclaration":
parts.push(printTypeScriptModifiers(path$$1, options, print), "import ", path$$1.call(print, "name"), " = ", path$$1.call(print, "moduleReference"));
if (options.semi) {
parts.push(";");
}
return group$1(concat$4(parts));
case "TSExternalModuleReference":
return concat$4(["require(", path$$1.call(print, "expression"), ")"]);
case "TSModuleDeclaration":
{
var _parent10 = path$$1.getParentNode();
var isExternalModule = isLiteral(n.id);
var parentIsDeclaration = _parent10.type === "TSModuleDeclaration";
var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
if (parentIsDeclaration) {
parts.push(".");
} else {
if (n.declare === true) {
parts.push("declare ");
}
parts.push(printTypeScriptModifiers(path$$1, options, print)); // Global declaration looks like this:
// (declare)? global { ... }
var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(options.originalText.slice(options.locStart(n), options.locStart(n.id)));
if (!isGlobalDeclaration) {
parts.push(isExternalModule ? "module " : "namespace ");
}
}
parts.push(path$$1.call(print, "id"));
if (bodyIsDeclaration) {
parts.push(path$$1.call(print, "body"));
} else if (n.body) {
parts.push(" {", indent$2(concat$4([line$3, path$$1.call(function (bodyPath) {
return comments.printDanglingComments(bodyPath, options, true);
}, "body"), group$1(path$$1.call(print, "body"))])), line$3, "}");
} else {
parts.push(semi);
}
return concat$4(parts);
}
case "TSModuleBlock":
return path$$1.call(function (bodyPath) {
return printStatementSequence(bodyPath, options, print);
}, "body");
case "PrivateName":
return concat$4(["#", path$$1.call(print, "id")]);
case "TSConditionalType":
return formatTernaryOperator(path$$1, options, print, {
beforeParts: function beforeParts() {
return [path$$1.call(print, "checkType"), " ", "extends", " ", path$$1.call(print, "extendsType")];
},
shouldCheckJsx: false,
operatorName: "TSConditionalType",
consequentNode: "trueType",
alternateNode: "falseType",
testNode: "checkType",
breakNested: false
});
case "TSInferType":
return concat$4(["infer", " ", path$$1.call(print, "typeParameter")]);
case "InterpreterDirective":
parts.push("#!", n.value, hardline$3);
if (isNextLineEmpty$2(options.originalText, n, options)) {
parts.push(hardline$3);
}
return concat$4(parts);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(n.type));
}
}
function printStatementSequence(path$$1, options, print) {
var printed = [];
var bodyNode = path$$1.getNode();
var isClass = bodyNode.type === "ClassBody";
path$$1.map(function (stmtPath, i) {
var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
// "statements," it's safer simply to skip them.
/* istanbul ignore if */
if (!stmt) {
return;
} // Skip printing EmptyStatement nodes to avoid leaving stray
// semicolons lying around.
if (stmt.type === "EmptyStatement") {
return;
}
var stmtPrinted = print(stmtPath);
var text = options.originalText;
var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
// don't prepend the only JSX element in a program with semicolon
if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
if (stmt.comments && stmt.comments.some(function (comment) {
return comment.leading;
})) {
parts.push(print(stmtPath, {
needsSemi: true
}));
} else {
parts.push(";", stmtPrinted);
}
} else {
parts.push(stmtPrinted);
}
if (!options.semi && isClass) {
if (classPropMayCauseASIProblems(stmtPath)) {
parts.push(";");
} else if (stmt.type === "ClassProperty") {
var nextChild = bodyNode.body[i + 1];
if (classChildNeedsASIProtection(nextChild)) {
parts.push(";");
}
}
}
if (isNextLineEmpty$2(text, stmt, options) && !isLastStatement(stmtPath)) {
parts.push(hardline$3);
}
printed.push(concat$4(parts));
});
return join$2(hardline$3, printed);
}
function printPropertyKey(path$$1, options, print) {
var node = path$$1.getNode();
var key = node.key;
if (key.type === "Identifier" && !node.computed && options.parser === "json") {
// a -> "a"
return path$$1.call(function (keyPath) {
return comments.printComments(keyPath, function () {
return JSON.stringify(key.name);
}, options);
}, "key");
}
if (isStringLiteral(key) && isIdentifierName(key.value) && !node.computed && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty")) {
// 'a' -> a
return path$$1.call(function (keyPath) {
return comments.printComments(keyPath, function () {
return key.value;
}, options);
}, "key");
}
return path$$1.call(print, "key");
}
function printMethod(path$$1, options, print) {
var node = path$$1.getNode();
var semi = options.semi ? ";" : "";
var kind = node.kind;
var parts = [];
if (node.type === "ObjectMethod" || node.type === "ClassMethod") {
node.value = node;
}
if (node.value.async) {
parts.push("async ");
}
if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
if (node.value.generator) {
parts.push("*");
}
} else {
assert.ok(kind === "get" || kind === "set");
parts.push(kind, " ");
}
var key = printPropertyKey(path$$1, options, print);
if (node.computed) {
key = concat$4(["[", key, "]"]);
}
parts.push(key, concat$4(path$$1.call(function (valuePath) {
return [printFunctionTypeParameters(valuePath, options, print), group$1(concat$4([printFunctionParams(valuePath, print, options), printReturnType(valuePath, print, options)]))];
}, "value")));
if (!node.value.body || node.value.body.length === 0) {
parts.push(semi);
} else {
parts.push(" ", path$$1.call(print, "value", "body"));
}
return concat$4(parts);
}
function couldGroupArg(arg) {
return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertionExpression" || arg.type === "TSAsExpression" || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && !arg.returnType && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || isJSXNode(arg.body));
}
function shouldGroupLastArg(args) {
var lastArg = getLast$4(args);
var penultimateArg = getPenultimate$1(args);
return !hasLeadingComment(lastArg) && !hasTrailingComment(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
// disable last element expansion.
!penultimateArg || penultimateArg.type !== lastArg.type);
}
function shouldGroupFirstArg(args) {
if (args.length !== 2) {
return false;
}
var firstArg = args[0];
var secondArg = args[1];
return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && !couldGroupArg(secondArg);
}
var functionCompositionFunctionNames = new Set(["pipe", // RxJS, Ramda
"pipeP", // Ramda
"pipeK", // Ramda
"compose", // Ramda, Redux
"composeFlipped", // Not from any library, but common in Haskell, so supported
"composeP", // Ramda
"composeK", // Ramda
"flow", // Lodash
"flowRight", // Lodash
"connect" // Redux
]);
function isFunctionCompositionFunction(node) {
switch (node.type) {
case "OptionalMemberExpression":
case "MemberExpression":
{
return isFunctionCompositionFunction(node.property);
}
case "Identifier":
{
return functionCompositionFunctionNames.has(node.name);
}
case "StringLiteral":
case "Literal":
{
return functionCompositionFunctionNames.has(node.value);
}
}
}
function printArgumentsList(path$$1, options, print) {
var node = path$$1.getValue();
var args = node.arguments;
if (args.length === 0) {
return concat$4(["(", comments.printDanglingComments(path$$1, options,
/* sameIndent */
true), ")"]);
}
var anyArgEmptyLine = false;
var hasEmptyLineFollowingFirstArg = false;
var lastArgIndex = args.length - 1;
var printedArguments = path$$1.map(function (argPath, index) {
var arg = argPath.getNode();
var parts = [print(argPath)];
if (index === lastArgIndex) {// do nothing
} else if (isNextLineEmpty$2(options.originalText, arg, options)) {
if (index === 0) {
hasEmptyLineFollowingFirstArg = true;
}
anyArgEmptyLine = true;
parts.push(",", hardline$3, hardline$3);
} else {
parts.push(",", line$3);
}
return concat$4(parts);
}, "arguments");
var maybeTrailingComma = shouldPrintComma(options, "all") ? "," : "";
function allArgsBrokenOut() {
return group$1(concat$4(["(", indent$2(concat$4([line$3, concat$4(printedArguments)])), maybeTrailingComma, line$3, ")"]), {
shouldBreak: true
});
} // We want to get
// pipe(
// x => x + 1,
// x => x - 1
// )
// here, but not
// process.stdout.pipe(socket)
if (isFunctionCompositionFunction(node.callee) && args.length > 1) {
return allArgsBrokenOut();
}
var shouldGroupFirst = shouldGroupFirstArg(args);
var shouldGroupLast = shouldGroupLastArg(args);
if (shouldGroupFirst || shouldGroupLast) {
var shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine; // We want to print the last argument with a special flag
var printedExpanded;
var i = 0;
path$$1.each(function (argPath) {
if (shouldGroupFirst && i === 0) {
printedExpanded = [concat$4([argPath.call(function (p) {
return print(p, {
expandFirstArg: true
});
}), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$3 : line$3, hasEmptyLineFollowingFirstArg ? hardline$3 : ""])].concat(printedArguments.slice(1));
}
if (shouldGroupLast && i === args.length - 1) {
printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) {
return print(p, {
expandLastArg: true
});
}));
}
i++;
}, "arguments");
var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
return concat$4([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([concat$4([ifBreak$1(indent$2(concat$4(["(", softline$1, concat$4(printedExpanded)])), concat$4(["(", concat$4(printedExpanded)])), somePrintedArgumentsWillBreak ? concat$4([ifBreak$1(maybeTrailingComma), softline$1]) : "", ")"]), shouldGroupFirst ? concat$4(["(", group$1(printedExpanded[0], {
shouldBreak: true
}), concat$4(printedExpanded.slice(1)), ")"]) : concat$4(["(", concat$4(printedArguments.slice(0, -1)), group$1(getLast$4(printedExpanded), {
shouldBreak: true
}), ")"]), allArgsBrokenOut()], {
shouldBreak
})]);
}
return group$1(concat$4(["(", indent$2(concat$4([softline$1, concat$4(printedArguments)])), ifBreak$1(shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]), {
shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
});
}
function printTypeAnnotation(path$$1, options, print) {
var node = path$$1.getValue();
if (!node.typeAnnotation) {
return "";
}
var parentNode = path$$1.getParentNode();
var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
if (isFlowAnnotationComment(options.originalText, node.typeAnnotation, options)) {
return concat$4([" /*: ", path$$1.call(print, "typeAnnotation"), " */"]);
}
return concat$4([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path$$1.call(print, "typeAnnotation")]);
}
function printFunctionTypeParameters(path$$1, options, print) {
var fun = path$$1.getValue();
if (fun.typeArguments) {
return path$$1.call(print, "typeArguments");
}
if (fun.typeParameters) {
return path$$1.call(print, "typeParameters");
}
return "";
}
function printFunctionParams(path$$1, print, options, expandArg, printTypeParams) {
var fun = path$$1.getValue();
var paramsField = fun.parameters ? "parameters" : "params";
var typeParams = printTypeParams ? printFunctionTypeParameters(path$$1, options, print) : "";
var printed = [];
if (fun[paramsField]) {
printed = path$$1.map(print, paramsField);
}
if (fun.rest) {
printed.push(concat$4(["...", path$$1.call(print, "rest")]));
}
if (printed.length === 0) {
return concat$4([typeParams, "(", comments.printDanglingComments(path$$1, options,
/* sameIndent */
true, function (comment) {
return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
}), ")"]);
}
var lastParam = getLast$4(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
// params of the first/last argument, we dont want the arguments to break and instead
// want the whole expression to be on a new line.
//
// Good: Bad:
// verylongcall( verylongcall((
// (a, b) => { a,
// } b,
// }) ) => {
// })
if (expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
return n.comments;
}))) {
return group$1(concat$4([removeLines$1(typeParams), "(", join$2(", ", printed.map(removeLines$1)), ")"]));
} // Single object destructuring should hug
//
// function({
// a,
// b,
// c
// }) {}
if (shouldHugArguments(fun)) {
return concat$4([typeParams, "(", join$2(", ", printed), ")"]);
}
var parent = path$$1.getParentNode(); // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (isTestCall(parent)) {
return concat$4([typeParams, "(", join$2(", ", printed), ")"]);
}
var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
var isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction(parent, options) || isTypeAnnotationAFunction(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && flowTypeAnnotations.indexOf(fun[paramsField][0].typeAnnotation.type) !== -1 && !(fun[paramsField][0].typeAnnotation.type === "GenericTypeAnnotation" && fun[paramsField][0].typeAnnotation.typeParameters) && !fun.rest;
if (isFlowShorthandWithOneArg) {
if (options.arrowParens === "always") {
return concat$4(["(", concat$4(printed), ")"]);
}
return concat$4(printed);
}
var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
return concat$4([typeParams, "(", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]);
}
function shouldPrintParamsWithoutParens(path$$1, options) {
if (options.arrowParens === "always") {
return false;
}
if (options.arrowParens === "avoid") {
var node = path$$1.getValue();
return canPrintParamsWithoutParens(node);
} // Fallback default; should be unreachable
return false;
}
function canPrintParamsWithoutParens(node) {
return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
}
function printFunctionDeclaration(path$$1, print, options) {
var n = path$$1.getValue();
var parts = [];
if (n.async) {
parts.push("async ");
}
parts.push("function");
if (n.generator) {
parts.push("*");
}
if (n.id) {
parts.push(" ", path$$1.call(print, "id"));
}
parts.push(printFunctionTypeParameters(path$$1, options, print), group$1(concat$4([printFunctionParams(path$$1, print, options), printReturnType(path$$1, print, options)])), n.body ? " " : "", path$$1.call(print, "body"));
return concat$4(parts);
}
function printObjectMethod(path$$1, options, print) {
var objMethod = path$$1.getValue();
var parts = [];
if (objMethod.async) {
parts.push("async ");
}
if (objMethod.generator) {
parts.push("*");
}
if (objMethod.method || objMethod.kind === "get" || objMethod.kind === "set") {
return printMethod(path$$1, options, print);
}
var key = printPropertyKey(path$$1, options, print);
if (objMethod.computed) {
parts.push("[", key, "]");
} else {
parts.push(key);
}
parts.push(printFunctionTypeParameters(path$$1, options, print), group$1(concat$4([printFunctionParams(path$$1, print, options), printReturnType(path$$1, print, options)])), " ", path$$1.call(print, "body"));
return concat$4(parts);
}
function printReturnType(path$$1, print, options) {
var n = path$$1.getValue();
var returnType = path$$1.call(print, "returnType");
if (n.returnType && isFlowAnnotationComment(options.originalText, n.returnType, options)) {
return concat$4([" /*: ", returnType, " */"]);
}
var parts = [returnType]; // prepend colon to TypeScript type annotation
if (n.returnType && n.returnType.typeAnnotation) {
parts.unshift(": ");
}
if (n.predicate) {
// The return type will already add the colon, but otherwise we
// need to do it ourselves
parts.push(n.returnType ? " " : ": ", path$$1.call(print, "predicate"));
}
return concat$4(parts);
}
function printExportDeclaration(path$$1, options, print) {
var decl = path$$1.getValue();
var semi = options.semi ? ";" : "";
var parts = ["export "];
var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration";
if (isDefault) {
parts.push("default ");
}
parts.push(comments.printDanglingComments(path$$1, options,
/* sameIndent */
true));
if (needsHardlineAfterDanglingComment(decl)) {
parts.push(hardline$3);
}
if (decl.declaration) {
parts.push(path$$1.call(print, "declaration"));
if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSAbstractClassDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction") {
parts.push(semi);
}
} else {
if (decl.specifiers && decl.specifiers.length > 0) {
var specifiers = [];
var defaultSpecifiers = [];
var namespaceSpecifiers = [];
path$$1.each(function (specifierPath) {
var specifierType = path$$1.getValue().type;
if (specifierType === "ExportSpecifier") {
specifiers.push(print(specifierPath));
} else if (specifierType === "ExportDefaultSpecifier") {
defaultSpecifiers.push(print(specifierPath));
} else if (specifierType === "ExportNamespaceSpecifier") {
namespaceSpecifiers.push(concat$4(["* as ", print(specifierPath)]));
}
}, "specifiers");
var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
parts.push(decl.exportKind === "type" ? "type " : "", concat$4(defaultSpecifiers), concat$4([isDefaultFollowed ? ", " : ""]), concat$4(namespaceSpecifiers), concat$4([isNamespaceFollowed ? ", " : ""]), specifiers.length !== 0 ? group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, join$2(concat$4([",", line$3]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$3 : softline$1, "}"])) : "");
} else {
parts.push("{}");
}
if (decl.source) {
parts.push(" from ", path$$1.call(print, "source"));
}
parts.push(semi);
}
return concat$4(parts);
}
function printFlowDeclaration(path$$1, parts) {
var parentExportDecl = getParentExportDeclaration$1(path$$1);
if (parentExportDecl) {
assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
} else {
// If the parent node has type DeclareExportDeclaration, then it
// will be responsible for printing the "declare" token. Otherwise
// it needs to be printed with this non-exported declaration node.
parts.unshift("declare ");
}
return concat$4(parts);
}
function getFlowVariance(path$$1) {
if (!path$$1.variance) {
return null;
} // Babylon 7.0 currently uses variance node type, and flow should
// follow suit soon:
// https://github.com/babel/babel/issues/4722
var variance = path$$1.variance.kind || path$$1.variance;
switch (variance) {
case "plus":
return "+";
case "minus":
return "-";
default:
/* istanbul ignore next */
return variance;
}
}
function printTypeScriptModifiers(path$$1, options, print) {
var n = path$$1.getValue();
if (!n.modifiers || !n.modifiers.length) {
return "";
}
return concat$4([join$2(" ", path$$1.map(print, "modifiers")), " "]);
}
function printTypeParameters(path$$1, options, print, paramsKey) {
var n = path$$1.getValue();
if (!n[paramsKey]) {
return "";
} // for TypeParameterDeclaration typeParameters is a single node
if (!Array.isArray(n[paramsKey])) {
return path$$1.call(print, paramsKey);
}
var grandparent = path$$1.getNode(2);
var isParameterInTestCall = grandparent != null && isTestCall(grandparent);
var shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation");
if (shouldInline) {
return concat$4(["<", join$2(", ", path$$1.map(print, paramsKey)), ">"]);
}
return group$1(concat$4(["<", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), path$$1.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && shouldPrintComma(options, "all") ? "," : ""), softline$1, ">"]));
}
function printClass(path$$1, options, print) {
var n = path$$1.getValue();
var parts = [];
if (n.type === "TSAbstractClassDeclaration") {
parts.push("abstract ");
}
parts.push("class");
if (n.id) {
parts.push(" ", path$$1.call(print, "id"));
}
parts.push(path$$1.call(print, "typeParameters"));
var partsGroup = [];
if (n.superClass) {
var printed = concat$4(["extends ", path$$1.call(print, "superClass"), path$$1.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
// If there is only on extends and there are not comments
if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
parts.push(concat$4([" ", path$$1.call(function (superClass) {
return comments.printComments(superClass, function () {
return printed;
}, options);
}, "superClass")]));
} else {
partsGroup.push(group$1(concat$4([line$3, path$$1.call(function (superClass) {
return comments.printComments(superClass, function () {
return printed;
}, options);
}, "superClass")])));
}
} else if (n.extends && n.extends.length > 0) {
parts.push(" extends ", join$2(", ", path$$1.map(print, "extends")));
}
if (n["mixins"] && n["mixins"].length > 0) {
partsGroup.push(line$3, "mixins ", group$1(indent$2(join$2(concat$4([",", line$3]), path$$1.map(print, "mixins")))));
}
if (n["implements"] && n["implements"].length > 0) {
partsGroup.push(line$3, "implements", group$1(indent$2(concat$4([line$3, join$2(concat$4([",", line$3]), path$$1.map(print, "implements"))]))));
}
if (partsGroup.length > 0) {
parts.push(group$1(indent$2(concat$4(partsGroup))));
}
if (n.body && n.body.comments && hasLeadingOwnLineComment(options.originalText, n.body, options)) {
parts.push(hardline$3);
} else {
parts.push(" ");
}
parts.push(path$$1.call(print, "body"));
return parts;
}
function printOptionalToken(path$$1) {
var node = path$$1.getValue();
if (!node.optional) {
return "";
}
if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
return "?.";
}
return "?";
}
function printMemberLookup(path$$1, options, print) {
var property = path$$1.call(print, "property");
var n = path$$1.getValue();
var optional = printOptionalToken(path$$1);
if (!n.computed) {
return concat$4([optional, ".", property]);
}
if (!n.property || isNumericLiteral(n.property)) {
return concat$4([optional, "[", property, "]"]);
}
return group$1(concat$4([optional, "[", indent$2(concat$4([softline$1, property])), softline$1, "]"]));
}
function printBindExpressionCallee(path$$1, options, print) {
return concat$4(["::", path$$1.call(print, "callee")]);
} // We detect calls on member expressions specially to format a
// common pattern better. The pattern we are looking for is this:
//
// arr
// .map(x => x + 1)
// .filter(x => x > 10)
// .some(x => x % 2)
//
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
function printMemberChain(path$$1, options, print) {
// The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberExpression(CallExpression(Identifier)))
// and we transform it into
// [Identifier, CallExpression, MemberExpression, CallExpression]
var printedNodes = []; // Here we try to retain one typed empty line after each call expression or
// the first group whether it is in parentheses or not
function shouldInsertEmptyLineAfter(node) {
var originalText = options.originalText;
var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options);
var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
// line after that parenthesis
if (nextChar == ")") {
return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options);
}
return isNextLineEmpty$2(originalText, node, options);
}
function rec(path$$1) {
var node = path$$1.getValue();
if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
printedNodes.unshift({
node: node,
printed: concat$4([comments.printComments(path$$1, function () {
return concat$4([printOptionalToken(path$$1), printFunctionTypeParameters(path$$1, options, print), printArgumentsList(path$$1, options, print)]);
}, options), shouldInsertEmptyLineAfter(node) ? hardline$3 : ""])
});
path$$1.call(function (callee) {
return rec(callee);
}, "callee");
} else if (isMemberish(node)) {
printedNodes.unshift({
node: node,
needsParens: needsParens_1(path$$1, options),
printed: comments.printComments(path$$1, function () {
return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path$$1, options, print) : printBindExpressionCallee(path$$1, options, print);
}, options)
});
path$$1.call(function (object) {
return rec(object);
}, "object");
} else if (node.type === "TSNonNullExpression") {
printedNodes.unshift({
node: node,
printed: comments.printComments(path$$1, function () {
return "!";
}, options)
});
path$$1.call(function (expression) {
return rec(expression);
}, "expression");
} else {
printedNodes.unshift({
node: node,
printed: path$$1.call(print)
});
}
} // Note: the comments of the root node have already been printed, so we
// need to extract this first call without printing them as they would
// if handled inside of the recursive call.
var node = path$$1.getValue();
printedNodes.unshift({
node,
printed: concat$4([printOptionalToken(path$$1), printFunctionTypeParameters(path$$1, options, print), printArgumentsList(path$$1, options, print)])
});
path$$1.call(function (callee) {
return rec(callee);
}, "callee"); // Once we have a linear list of printed nodes, we want to create groups out
// of it.
//
// a().b.c().d().e
// will be grouped as
// [
// [Identifier, CallExpression],
// [MemberExpression, MemberExpression, CallExpression],
// [MemberExpression, CallExpression],
// [MemberExpression],
// ]
// so that we can print it as
// a()
// .b.c()
// .d()
// .e
// The first group is the first node followed by
// - as many CallExpression as possible
// < fn()()() >.something()
// - as many array acessors as possible
// < fn()[0][1][2] >.something()
// - then, as many MemberExpression as possible but the last one
// < this.items >.something()
var groups = [];
var currentGroup = [printedNodes[0]];
var i = 1;
for (; i < printedNodes.length; ++i) {
if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
for (; i + 1 < printedNodes.length; ++i) {
if (isMemberish(printedNodes[i].node) && isMemberish(printedNodes[i + 1].node)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
}
groups.push(currentGroup);
currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
// a sequence of CallExpression. To compute it, we keep adding things to the
// group until we has seen a CallExpression in the past and reach a
// MemberExpression
var hasSeenCallExpression = false;
for (; i < printedNodes.length; ++i) {
if (hasSeenCallExpression && isMemberish(printedNodes[i].node)) {
// [0] should be appended at the end of the group instead of the
// beginning of the next one
if (printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
continue;
}
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) {
return comment.trailing;
})) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
} // There are cases like Object.keys(), Observable.of(), _.values() where
// they are the subject of all the chained calls and therefore should
// be kept on the same line:
//
// Object.keys(items)
// .filter(x => x)
// .map(x => x)
//
// In order to detect those cases, we use an heuristic: if the first
// node is an identifier with the name starting with a capital
// letter or just a sequence of _$. The rationale is that they are
// likely to be factories.
function isFactory(name) {
return /^[A-Z]|^[_$]+$/.test(name);
} // In case the Identifier is shorter than tab width, we can keep the
// first call in a single line, if it's an ExpressionStatement.
//
// d3.scaleLinear()
// .domain([0, 100])
// .range([0, width]);
//
function isShort(name) {
return name.length <= options.tabWidth;
}
function shouldNotWrap(groups) {
var parent = path$$1.getParentNode();
var isExpression = parent && parent.type === "ExpressionStatement";
var hasComputed = groups[1].length && groups[1][0].node.computed;
if (groups[0].length === 1) {
var firstNode = groups[0][0].node;
return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
}
var lastNode = getLast$4(groups[0]).node;
return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
}
var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
function printGroup(printedGroup) {
var result = [];
for (var _i3 = 0; _i3 < printedGroup.length; _i3++) {
// Checks if the next node (i.e. the parent node) needs parens
// and print accordingl y
if (printedGroup[_i3 + 1] && printedGroup[_i3 + 1].needsParens) {
result.push("(", printedGroup[_i3].printed, printedGroup[_i3 + 1].printed, ")");
_i3++;
} else {
result.push(printedGroup[_i3].printed);
}
}
return concat$4(result);
}
function printIndentedGroup(groups) {
if (groups.length === 0) {
return "";
}
return indent$2(group$1(concat$4([hardline$3, join$2(hardline$3, groups.map(printGroup))])));
}
var printedGroups = groups.map(printGroup);
var oneLine = concat$4(printedGroups);
var cutoff = shouldMerge ? 3 : 2;
var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) {
return res.concat(group);
}, []);
var hasComment = flatGroups.slice(1, -1).some(function (node) {
return hasLeadingComment(node.node);
}) || flatGroups.slice(0, -1).some(function (node) {
return hasTrailingComment(node.node);
}) || groups[cutoff] && hasLeadingComment(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.length <= cutoff && !hasComment) {
return group$1(oneLine);
} // Find out the last node in the first group and check if it has an
// empty line after
var lastNodeBeforeIndent = getLast$4(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
var expanded = concat$4([printGroup(groups[0]), shouldMerge ? concat$4(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$3 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
var callExpressionCount = printedNodes.filter(function (tuple) {
return tuple.node.type === "CallExpression" || tuple.node.type === "OptionalCallExpression";
}).length; // We don't want to print in one line if there's:
// * A comment.
// * 3 or more chained calls.
// * Any group but the last one has a hard line.
// If the last group is a function it's okay to inline if it fits.
if (hasComment || callExpressionCount >= 3 || printedGroups.slice(0, -1).some(willBreak$1)) {
return group$1(expanded);
}
return concat$4([// We only need to check `oneLine` because if `expanded` is chosen
// that means that the parent group has already been broken
// naturally
willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]);
}
function isJSXNode(node) {
return node.type === "JSXElement" || node.type === "JSXFragment" || node.type === "TSJsxFragment";
}
function isEmptyJSXElement(node) {
if (node.children.length === 0) {
return true;
}
if (node.children.length > 1) {
return false;
} // if there is one text child and does not contain any meaningful text
// we can treat the element as empty.
var child = node.children[0];
return isLiteral(child) && !isMeaningfulJSXText(child);
} // Only space, newline, carriage return, and tab are treated as whitespace
// inside JSX.
var jsxWhitespaceChars = " \n\r\t";
var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]");
var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); // Meaningful if it contains non-whitespace characters,
// or it contains whitespace without a new line.
function isMeaningfulJSXText(node) {
return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
}
function conditionalExpressionChainContainsJSX(node) {
return Boolean(getConditionalChainContents(node).find(isJSXNode));
} // If we have nested conditional expressions, we want to print them in JSX mode
// if there's at least one JSXElement somewhere in the tree.
//
// A conditional expression chain like this should be printed in normal mode,
// because there aren't JSXElements anywhere in it:
//
// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
//
// But a conditional expression chain like this should be printed in JSX mode,
// because there is a JSXElement in the last ConditionalExpression:
//
// isA ? "A" : isB ? "B" : isC ? "C" :
Unknown;
//
// This type of ConditionalExpression chain is structured like this in the AST:
//
// ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ...,
// }
// }
// }
//
// We want to traverse over that shape and convert it into a flat structure so
// that we can find if there's a JSXElement somewhere inside.
function getConditionalChainContents(node) {
// Given this code:
//
// // Using a ConditionalExpression as the consequent is uncommon, but should
// // be handled.
// A ? B : C ? D : E ? F ? G : H : I
//
// which has this AST:
//
// ConditionalExpression {
// test: Identifier(A),
// consequent: Identifier(B),
// alternate: ConditionalExpression {
// test: Identifier(C),
// consequent: Identifier(D),
// alternate: ConditionalExpression {
// test: Identifier(E),
// consequent: ConditionalExpression {
// test: Identifier(F),
// consequent: Identifier(G),
// alternate: Identifier(H),
// },
// alternate: Identifier(I),
// }
// }
// }
//
// we should return this Array:
//
// [
// Identifier(A),
// Identifier(B),
// Identifier(C),
// Identifier(D),
// Identifier(E),
// Identifier(F),
// Identifier(G),
// Identifier(H),
// Identifier(I)
// ];
//
// This loses the information about whether each node was the test,
// consequent, or alternate, but we don't care about that here- we are only
// flattening this structure to find if there's any JSXElements inside.
var nonConditionalExpressions = [];
function recurse(node) {
if (node.type === "ConditionalExpression") {
recurse(node.test);
recurse(node.consequent);
recurse(node.alternate);
} else {
nonConditionalExpressions.push(node);
}
}
recurse(node);
return nonConditionalExpressions;
} // Detect an expression node representing `{" "}`
function isJSXWhitespaceExpression(node) {
return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
} // JSX Children are strange, mostly for two reasons:
// 1. JSX reads newlines into string values, instead of skipping them like JS
// 2. up to one whitespace between elements within a line is significant,
// but not between lines.
//
// Leading, trailing, and lone whitespace all need to
// turn themselves into the rather ugly `{' '}` when breaking.
//
// We print JSX using the `fill` doc primitive.
// This requires that we give it an array of alternating
// content and whitespace elements.
// To ensure this we add dummy `""` content elements as needed.
function printJSXChildren(path$$1, options, print, jsxWhitespace) {
var n = path$$1.getValue();
var children = []; // using `map` instead of `each` because it provides `i`
path$$1.map(function (childPath, i) {
var child = childPath.getValue();
if (isLiteral(child)) {
var text = rawText(child); // Contains a non-whitespace character
if (isMeaningfulJSXText(child)) {
var words = text.split(matchJsxWhitespaceRegex); // Starts with whitespace
if (words[0] === "") {
children.push("");
words.shift();
if (/\n/.test(words[0])) {
children.push(hardline$3);
} else {
children.push(jsxWhitespace);
}
words.shift();
}
var endWhitespace; // Ends with whitespace
if (getLast$4(words) === "") {
words.pop();
endWhitespace = words.pop();
} // This was whitespace only without a new line.
if (words.length === 0) {
return;
}
words.forEach(function (word, i) {
if (i % 2 === 1) {
children.push(line$3);
} else {
children.push(word);
}
});
if (endWhitespace !== undefined) {
if (/\n/.test(endWhitespace)) {
children.push(hardline$3);
} else {
children.push(jsxWhitespace);
}
} else {
// Ideally this would be a `hardline` to allow a break between
// tags and text.
// Unfortunately Facebook have a custom translation pipeline
// (https://github.com/prettier/prettier/issues/1581#issuecomment-300975032)
// that uses the JSX syntax, but does not follow the React whitespace
// rules.
// Ensuring that we never have a break between tags and text in JSX
// will allow Facebook to adopt Prettier without too much of an
// adverse effect on formatting algorithm.
children.push("");
}
} else if (/\n/.test(text)) {
// Keep (up to one) blank line between tags/expressions/text.
// Note: We don't keep blank lines between text elements.
if (text.match(/\n/g).length > 1) {
children.push("");
children.push(hardline$3);
}
} else {
children.push("");
children.push(jsxWhitespace);
}
} else {
var printedChild = print(childPath);
children.push(printedChild);
var next = n.children[i + 1];
var directlyFollowedByMeaningfulText = next && isMeaningfulJSXText(next) && !/^[ \n\r\t]/.test(rawText(next));
if (directlyFollowedByMeaningfulText) {
// Potentially this could be a hardline as well.
// See the comment above about the Facebook translation pipeline as
// to why this is an empty string.
children.push("");
} else {
children.push(hardline$3);
}
}
}, "children");
return children;
} // JSX expands children from the inside-out, instead of the outside-in.
// This is both to break children before attributes,
// and to ensure that when children break, their parents do as well.
//
// Any element that is written without any newlines and fits on a single line
// is left that way.
// Not only that, any user-written-line containing multiple JSX siblings
// should also be kept on one line if possible,
// so each user-written-line is wrapped in its own group.
//
// Elements that contain newlines or don't fit on a single line (recursively)
// are fully-split, using hardline and shouldBreak: true.
//
// To support that case properly, all leading and trailing spaces
// are stripped from the list of children, and replaced with a single hardline.
function printJSXElement(path$$1, options, print) {
var n = path$$1.getValue(); // Turn
into
if (n.type === "JSXElement" && isEmptyJSXElement(n)) {
n.openingElement.selfClosing = true;
return path$$1.call(print, "openingElement");
}
var openingLines = n.type === "JSXElement" ? path$$1.call(print, "openingElement") : path$$1.call(print, "openingFragment");
var closingLines = n.type === "JSXElement" ? path$$1.call(print, "closingElement") : path$$1.call(print, "closingFragment");
if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
return concat$4([openingLines, concat$4(path$$1.map(print, "children")), closingLines]);
} // Convert `{" "}` to text nodes containing a space.
// This makes it easy to turn them into `jsxWhitespace` which
// can then print as either a space or `{" "}` when breaking.
n.children = n.children.map(function (child) {
if (isJSXWhitespaceExpression(child)) {
return {
type: "JSXText",
value: " ",
raw: " "
};
}
return child;
});
var containsTag = n.children.filter(isJSXNode).length > 0;
var containsMultipleExpressions = n.children.filter(function (child) {
return child.type === "JSXExpressionContainer";
}).length > 1;
var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
var jsxWhitespace = ifBreak$1(concat$4([rawJsxWhitespace, softline$1]), " ");
var children = printJSXChildren(path$$1, options, print, jsxWhitespace);
var containsText = n.children.filter(function (child) {
return isMeaningfulJSXText(child);
}).length > 0; // We can end up we multiple whitespace elements with empty string
// content between them.
// We need to remove empty whitespace and softlines before JSX whitespace
// to get the correct output.
for (var i = children.length - 2; i >= 0; i--) {
var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
var isPairOfHardlines = children[i] === hardline$3 && children[i + 1] === "" && children[i + 2] === hardline$3;
var isLineFollowedByJSXWhitespace = (children[i] === softline$1 || children[i] === hardline$3) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$1 || children[i + 2] === hardline$3);
var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace) {
children.splice(i, 2);
} else if (isJSXWhitespaceFollowedByLine) {
children.splice(i + 1, 2);
}
} // Trim trailing lines (or empty strings)
while (children.length && (isLineNext$1(getLast$4(children)) || isEmpty$1(getLast$4(children)))) {
children.pop();
} // Trim leading lines (or empty strings)
while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
children.shift();
children.shift();
} // Tweak how we format children if outputting this element over multiple lines.
// Also detect whether we will force this element to output over multiple lines.
var multilineChildren = [];
children.forEach(function (child, i) {
// There are a number of situations where we need to ensure we display
// whitespace as `{" "}` when outputting this element over multiple lines.
if (child === jsxWhitespace) {
if (i === 1 && children[i - 1] === "") {
if (children.length === 2) {
// Solitary whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} // Leading whitespace
multilineChildren.push(concat$4([rawJsxWhitespace, hardline$3]));
return;
} else if (i === children.length - 1) {
// Trailing whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} else if (children[i - 1] === "" && children[i - 2] === hardline$3) {
// Whitespace after line break
multilineChildren.push(rawJsxWhitespace);
return;
}
}
multilineChildren.push(child);
if (willBreak$1(child)) {
forcedBreak = true;
}
}); // If there is text we use `fill` to fit as much onto each line as possible.
// When there is no text (just tags and expressions) we use `group`
// to output each on a separate line.
var content = containsText ? fill$2(multilineChildren) : group$1(concat$4(multilineChildren), {
shouldBreak: true
});
var multiLineElem = group$1(concat$4([openingLines, indent$2(concat$4([hardline$3, content])), hardline$3, closingLines]));
if (forcedBreak) {
return multiLineElem;
}
return conditionalGroup$1([group$1(concat$4([openingLines, concat$4(children), closingLines])), multiLineElem]);
}
function maybeWrapJSXElementInParens(path$$1, elem) {
var parent = path$$1.getParentNode();
if (!parent) {
return elem;
}
var NO_WRAP_PARENTS = {
ArrayExpression: true,
JSXAttribute: true,
JSXElement: true,
JSXExpressionContainer: true,
JSXFragment: true,
TSJsxFragment: true,
ExpressionStatement: true,
CallExpression: true,
OptionalCallExpression: true,
ConditionalExpression: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
}
return group$1(concat$4([ifBreak$1("("), indent$2(concat$4([softline$1, elem])), softline$1, ifBreak$1(")")]));
}
function isBinaryish(node) {
return node.type === "BinaryExpression" || node.type === "LogicalExpression";
}
function isMemberish(node) {
return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
}
function shouldInlineLogicalExpression(node) {
if (node.type !== "LogicalExpression") {
return false;
}
if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
return true;
}
if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
return true;
}
if (isJSXNode(node.right)) {
return true;
}
return false;
} // For binary expressions to be consistent, we need to group
// subsequent operators with the same precedence level under a single
// group. Otherwise they will be nested such that some of them break
// onto new lines but not all. Operators with the same precedence
// level should either all break or not. Because we group them by
// precedence level and the AST is structured based on precedence
// level, things are naturally broken up correctly, i.e. `&&` is
// broken before `+`.
function printBinaryishExpressions(path$$1, print, options, isNested, isInsideParenthesis) {
var parts = [];
var node = path$$1.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
if (isBinaryish(node)) {
// Put all operators with the same precedence level in the same
// group. The reason we only need to do this with the `left`
// expression is because given an expression like `1 + 2 - 3`, it
// is always parsed like `((1 + 2) - 3)`, meaning the `left` side
// is where the rest of the expression will exist. Binary
// expressions on the right side mean they have a difference
// precedence level and should be treated as a separate group, so
// print them normally. (This doesn't hold for the `**` operator,
// which is unique in that it is right-associative.)
if (shouldFlatten$1(node.operator, node.left.operator)) {
// Flatten them out by recursively calling this function.
parts = parts.concat(path$$1.call(function (left) {
return printBinaryishExpressions(left, print, options,
/* isNested */
true, isInsideParenthesis);
}, "left"));
} else {
parts.push(path$$1.call(print, "left"));
}
var shouldInline = shouldInlineLogicalExpression(node);
var lineBeforeOperator = node.operator === "|>";
var right = shouldInline ? concat$4([node.operator, " ", path$$1.call(print, "right")]) : concat$4([lineBeforeOperator ? softline$1 : "", node.operator, lineBeforeOperator ? " " : line$3, path$$1.call(print, "right")]); // If there's only a single binary expression, we want to create a group
// in order to avoid having a small right part like -1 be on its own line.
var parent = path$$1.getParentNode();
var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
parts.push(" ", shouldGroup ? group$1(right) : right); // The root comments are already printed, but we need to manually print
// the other ones since we don't call the normal print on BinaryExpression,
// only for the left and right parts
if (isNested && node.comments) {
parts = comments.printComments(path$$1, function () {
return concat$4(parts);
}, options);
}
} else {
// Our stopping case. Simply print the node normally.
parts.push(path$$1.call(print));
}
return parts;
}
function printAssignmentRight(leftNode, rightNode, printedRight, options) {
if (hasLeadingOwnLineComment(options.originalText, rightNode, options)) {
return indent$2(concat$4([hardline$3, printedRight]));
}
var canBreak = isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || (leftNode.type === "Identifier" || isStringLiteral(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral(rightNode) || isMemberExpressionChain(rightNode));
if (canBreak) {
return indent$2(concat$4([line$3, printedRight]));
}
return concat$4([" ", printedRight]);
}
function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
if (!rightNode) {
return printedLeft;
}
var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
return group$1(concat$4([printedLeft, operator, printed]));
}
function adjustClause(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return concat$4([" ", clause]);
}
return indent$2(concat$4([line$3, clause]));
}
function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
var raw = rawText(node);
var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
return printString$1(raw, options, isDirectiveLiteral);
}
function printRegex(node) {
var flags = node.flags.split("").sort().join("");
return `/${node.pattern}/${flags}`;
}
function isLastStatement(path$$1) {
var parent = path$$1.getParentNode();
if (!parent) {
return true;
}
var node = path$$1.getValue();
var body = (parent.body || parent.consequent).filter(function (stmt) {
return stmt.type !== "EmptyStatement";
});
return body && body[body.length - 1] === node;
}
function hasLeadingComment(node) {
return node.comments && node.comments.some(function (comment) {
return comment.leading;
});
}
function hasTrailingComment(node) {
return node.comments && node.comments.some(function (comment) {
return comment.trailing;
});
}
function hasLeadingOwnLineComment(text, node, options) {
if (isJSXNode(node)) {
return hasNodeIgnoreComment$1(node);
}
var res = node.comments && node.comments.some(function (comment) {
return comment.leading && hasNewline$2(text, options.locEnd(comment));
});
return res;
}
function hasNakedLeftSide(node) {
return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" && !node.object || node.type === "UpdateExpression" && !node.prefix;
}
function isFlowAnnotationComment(text, typeAnnotation, options) {
var start = options.locStart(typeAnnotation);
var end = skipWhitespace$1(text, options.locEnd(typeAnnotation));
return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/";
}
function getLeftSide(node) {
if (node.expressions) {
return node.expressions[0];
}
return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
}
function getLeftSidePathName(path$$1, node) {
if (node.expressions) {
return ["expressions", 0];
}
if (node.left) {
return ["left"];
}
if (node.test) {
return ["test"];
}
if (node.callee) {
return ["callee"];
}
if (node.object) {
return ["object"];
}
if (node.tag) {
return ["tag"];
}
if (node.argument) {
return ["argument"];
}
if (node.expression) {
return ["expression"];
}
throw new Error("Unexpected node has no left side", node);
}
function exprNeedsASIProtection(path$$1, options) {
var node = path$$1.getValue();
var maybeASIProblem = needsParens_1(path$$1, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path$$1, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode(node) || node.type === "BindExpression" || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
if (maybeASIProblem) {
return true;
}
if (!hasNakedLeftSide(node)) {
return false;
}
return path$$1.call.apply(path$$1, [function (childPath) {
return exprNeedsASIProtection(childPath, options);
}].concat(getLeftSidePathName(path$$1, node)));
}
function stmtNeedsASIProtection(path$$1, options) {
var node = path$$1.getNode();
if (node.type !== "ExpressionStatement") {
return false;
}
return path$$1.call(function (childPath) {
return exprNeedsASIProtection(childPath, options);
}, "expression");
}
function classPropMayCauseASIProblems(path$$1) {
var node = path$$1.getNode();
if (node.type !== "ClassProperty") {
return false;
}
var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
// so isn't properly tested yet.
if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
return true;
}
}
function classChildNeedsASIProtection(node) {
if (!node) {
return;
}
if (!node.computed) {
var name = node.key && node.key.name;
if (name === "in" || name === "instanceof") {
return true;
}
}
switch (node.type) {
case "ClassProperty":
case "TSAbstractClassProperty":
return node.computed;
case "MethodDefinition": // Flow
case "TSAbstractMethodDefinition": // TypeScript
case "ClassMethod":
{
// Babylon
var isAsync = node.value ? node.value.async : node.async;
var isGenerator = node.value ? node.value.generator : node.generator;
if (isAsync || node.static || node.kind === "get" || node.kind === "set") {
return false;
}
if (node.computed || isGenerator) {
return true;
}
return false;
}
default:
/* istanbul ignore next */
return false;
}
} // This recurses the return argument, looking for the first token
// (the leftmost leaf node) and, if it (or its parents) has any
// leadingComments, returns true (so it can be wrapped in parens).
function returnArgumentHasLeadingComment(options, argument) {
if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
return true;
}
if (hasNakedLeftSide(argument)) {
var leftMost = argument;
var newLeftMost;
while (newLeftMost = getLeftSide(leftMost)) {
leftMost = newLeftMost;
if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
return true;
}
}
}
return false;
}
function isMemberExpressionChain(node) {
if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
return false;
}
if (node.object.type === "Identifier") {
return true;
}
return isMemberExpressionChain(node.object);
} // Hack to differentiate between the following two which have the same ast
// type T = { method: () => void };
// type T = { method(): void };
function isObjectTypePropertyAFunction(node, options) {
return node.type === "ObjectTypeProperty" && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
} // TODO: This is a bad hack and we need a better way to distinguish between
// arrow functions and otherwise
function isFunctionNotation(node, options) {
return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
}
function isGetterOrSetter(node) {
return node.kind === "get" || node.kind === "set";
}
function sameLocStart(nodeA, nodeB, options) {
return options.locStart(nodeA) === options.locStart(nodeB);
} // Hack to differentiate between the following two which have the same ast
// declare function f(a): void;
// var f: (a) => void;
function isTypeAnnotationAFunction(node, options) {
return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
}
function isNodeStartingWithDeclare(node, options) {
if (!(options.parser === "flow" || options.parser === "typescript")) {
return false;
}
return options.originalText.slice(0, options.locStart(node)).match(/declare[ \t]*$/) || options.originalText.slice(node.range[0], node.range[1]).startsWith("declare ");
}
function shouldHugType(node) {
if (isObjectType(node)) {
return true;
}
if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
var voidCount = node.types.filter(function (n) {
return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword";
}).length;
var objectCount = node.types.filter(function (n) {
return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference";
}).length;
if (node.types.length - 1 === voidCount && objectCount > 0) {
return true;
}
}
return false;
}
function shouldHugArguments(fun) {
return fun && fun.params && fun.params.length === 1 && !fun.params[0].comments && (fun.params[0].type === "ObjectPattern" || fun.params[0].type === "ArrayPattern" || fun.params[0].type === "Identifier" && fun.params[0].typeAnnotation && (fun.params[0].typeAnnotation.type === "TypeAnnotation" || fun.params[0].typeAnnotation.type === "TSTypeAnnotation") && isObjectType(fun.params[0].typeAnnotation.typeAnnotation) || fun.params[0].type === "FunctionTypeParam" && isObjectType(fun.params[0].typeAnnotation) || fun.params[0].type === "AssignmentPattern" && (fun.params[0].left.type === "ObjectPattern" || fun.params[0].left.type === "ArrayPattern") && (fun.params[0].right.type === "Identifier" || fun.params[0].right.type === "ObjectExpression" && fun.params[0].right.properties.length === 0 || fun.params[0].right.type === "ArrayExpression" && fun.params[0].right.elements.length === 0)) && !fun.rest;
}
function templateLiteralHasNewLines(template) {
return template.quasis.some(function (quasi) {
return quasi.value.raw.includes("\n");
});
}
function isTemplateOnItsOwnLine(n, text, options) {
return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$2(text, options.locStart(n), {
backwards: true
});
}
function printArrayItems(path$$1, options, printPath, print) {
var printedElements = [];
var separatorParts = [];
path$$1.each(function (childPath) {
printedElements.push(concat$4(separatorParts));
printedElements.push(group$1(print(childPath)));
separatorParts = [",", line$3];
if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
separatorParts.push(softline$1);
}
}, printPath);
return concat$4(printedElements);
}
function hasDanglingComments(node) {
return node.comments && node.comments.some(function (comment) {
return !comment.leading && !comment.trailing;
});
}
function needsHardlineAfterDanglingComment(node) {
if (!node.comments) {
return false;
}
var lastDanglingComment = getLast$4(node.comments.filter(function (comment) {
return !comment.leading && !comment.trailing;
}));
return lastDanglingComment && !comments$3.isBlockComment(lastDanglingComment);
}
function isLiteral(node) {
return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
}
function isNumericLiteral(node) {
return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
}
function isStringLiteral(node) {
return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
}
function isObjectType(n) {
return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
}
var unitTestRe = /^(skip|[fx]?(it|describe|test))$/; // eg; `describe("some string", (done) => {})`
function isTestCall(n, parent) {
if (n.type !== "CallExpression") {
return false;
}
if (n.arguments.length === 1) {
if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
return isFunctionOrArrowExpression(n.arguments[0].type);
}
if (isUnitTestSetUp(n)) {
return isFunctionOrArrowExpression(n.arguments[0].type) || isAngularTestWrapper(n.arguments[0]);
}
} else if (n.arguments.length === 2) {
if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
return isFunctionOrArrowExpression(n.arguments[1].type) && n.arguments[1].params.length <= 1 || isAngularTestWrapper(n.arguments[1]);
}
}
return false;
}
function isSkipOrOnlyBlock(node) {
return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip");
}
function isTemplateLiteral(node) {
return node.type === "TemplateLiteral";
} // `inject` is used in AngularJS 1.x, `async` in Angular 2+
// example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
function isAngularTestWrapper(node) {
return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject");
}
function isFunctionOrArrowExpression(type) {
return type === "FunctionExpression" || type === "ArrowFunctionExpression";
}
function isUnitTestSetUp(n) {
var unitTestSetUpRe = /^(before|after)(Each|All)$/;
return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
}
function isTheOnlyJSXElementInMarkdown(options, path$$1) {
if (options.parentParser !== "markdown") {
return false;
}
var node = path$$1.getNode();
if (!node.expression || !isJSXNode(node.expression)) {
return false;
}
var parent = path$$1.getParentNode();
return parent.type === "Program" && parent.body.length == 1;
}
function willPrintOwnComments(path$$1) {
var node = path$$1.getValue();
var parent = path$$1.getParentNode();
return (node && isJSXNode(node) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && !hasIgnoreComment$1(path$$1);
}
function canAttachComment(node) {
return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import" && !(node.callee && node.callee.type === "Import");
}
function printComment$1(commentPath, options) {
var comment = commentPath.getValue();
switch (comment.type) {
case "CommentBlock":
case "Block":
{
if (isJsDocComment(comment)) {
var printed = printJsDocComment(comment); // We need to prevent an edge case of a previous trailing comment
// printed as a `lineSuffix` which causes the comments to be
// interleaved. See https://github.com/prettier/prettier/issues/4412
if (comment.trailing && !hasNewline$2(options.originalText, options.locStart(comment), {
backwards: true
})) {
return concat$4([hardline$3, printed]);
}
return printed;
}
var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/";
return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
}
case "CommentLine":
case "Line":
// Print shebangs with the proper comment characters
if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
return "#!" + comment.value.trimRight();
}
return "//" + comment.value.trimRight();
default:
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function isJsDocComment(comment) {
var lines = comment.value.split("\n");
return lines.length > 1 && lines.slice(0, lines.length - 1).every(function (line) {
return line.trim()[0] === "*";
});
}
function printJsDocComment(comment) {
var lines = comment.value.split("\n");
return concat$4(["/*", join$2(hardline$3, lines.map(function (line, index) {
return (index > 0 ? " " : "") + (index < lines.length - 1 ? line.trim() : line.trimLeft());
})), "*/"]);
}
function rawText(node) {
return node.extra ? node.extra.raw : node.raw;
}
var printerEstree = {
print: genericPrint$1,
embed: embed_1,
insertPragma,
massageAstNode: clean_1,
hasPrettierIgnore,
willPrintOwnComments,
canAttachComment,
printComment: printComment$1,
isBlockComment: comments$3.isBlockComment,
handleComments: {
ownLine: comments$3.handleOwnLineComment,
endOfLine: comments$3.handleEndOfLineComment,
remaining: comments$3.handleRemainingComment
}
};
var _require$$0$builders$2 = doc.builders;
var concat$6 = _require$$0$builders$2.concat;
var hardline$5 = _require$$0$builders$2.hardline;
var indent$4 = _require$$0$builders$2.indent;
var join$4 = _require$$0$builders$2.join;
function genericPrint$2(path$$1, options, print) {
var node = path$$1.getValue();
switch (node.type) {
case "ArrayExpression":
return node.elements.length === 0 ? "[]" : concat$6(["[", indent$4(concat$6([hardline$5, join$4(concat$6([",", hardline$5]), path$$1.map(print, "elements"))])), hardline$5, "]"]);
case "ObjectExpression":
return node.properties.length === 0 ? "{}" : concat$6(["{", indent$4(concat$6([hardline$5, join$4(concat$6([",", hardline$5]), path$$1.map(print, "properties"))])), hardline$5, "}"]);
case "ObjectProperty":
return concat$6([path$$1.call(print, "key"), ": ", path$$1.call(print, "value")]);
case "UnaryExpression":
return concat$6([node.operator === "+" ? "" : node.operator, path$$1.call(print, "argument")]);
case "NullLiteral":
return "null";
case "BooleanLiteral":
return node.value ? "true" : "false";
case "StringLiteral":
case "NumericLiteral":
return JSON.stringify(node.value);
case "Identifier":
return JSON.stringify(node.name);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(node.type));
}
}
function clean$2(node, newNode
/*, parent*/
) {
delete newNode.start;
delete newNode.end;
delete newNode.extra;
delete newNode.loc;
delete newNode.comments;
if (node.type === "Identifier") {
return {
type: "StringLiteral",
value: node.name
};
}
if (node.type === "UnaryExpression" && node.operator === "+") {
return newNode.argument;
}
}
var printerEstreeJson = {
print: genericPrint$2,
massageAstNode: clean$2
};
var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var commonOptions = {
bracketSpacing: {
since: "0.0.0",
category: CATEGORY_COMMON,
type: "boolean",
default: true,
description: "Print spaces between brackets.",
oppositeDescription: "Do not print spaces between brackets."
},
singleQuote: {
since: "0.0.0",
category: CATEGORY_COMMON,
type: "boolean",
default: false,
description: "Use single quotes instead of double quotes."
}
};
var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var options$4 = {
arrowParens: {
since: "1.9.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: "avoid",
description: "Include parentheses around a sole arrow function parameter.",
choices: [{
value: "avoid",
description: "Omit parens when possible. Example: `x => x`"
}, {
value: "always",
description: "Always include parens. Example: `(x) => x`"
}]
},
bracketSpacing: commonOptions.bracketSpacing,
jsxBracketSameLine: {
since: "0.17.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Put > on the last line instead of at a new line."
},
semi: {
since: "1.0.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: true,
description: "Print semicolons.",
oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
},
singleQuote: commonOptions.singleQuote,
trailingComma: {
since: "0.0.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: [{
since: "0.0.0",
value: false
}, {
since: "0.19.0",
value: "none"
}],
description: "Print trailing commas wherever possible when multi-line.",
choices: [{
value: "none",
description: "No trailing commas."
}, {
value: "es5",
description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
}, {
value: "all",
description: "Trailing commas wherever possible (including function arguments)."
}, {
value: true,
deprecated: "0.19.0",
redirect: "es5"
}, {
value: false,
deprecated: "0.19.0",
redirect: "none"
}]
}
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages = [{
name: "JavaScript",
since: "0.0.0",
parsers: ["babylon", "flow"],
group: "JavaScript",
tmScope: "source.js",
aceMode: "javascript",
codemirrorMode: "javascript",
codemirrorMimeType: "text/javascript",
aliases: ["js", "node"],
extensions: [".js", "._js", ".bones", ".es", ".es6", ".frag", ".gs", ".jake", ".jsb", ".jscad", ".jsfl", ".jsm", ".jss", ".mjs", ".njs", ".pac", ".sjs", ".ssjs", ".xsjs", ".xsjslib"],
filenames: ["Jakefile"],
linguistLanguageId: 183,
vscodeLanguageIds: ["javascript"]
}, {
name: "JSX",
since: "0.0.0",
parsers: ["babylon", "flow"],
group: "JavaScript",
extensions: [".jsx"],
tmScope: "source.js.jsx",
aceMode: "javascript",
codemirrorMode: "jsx",
codemirrorMimeType: "text/jsx",
liguistLanguageId: 178,
vscodeLanguageIds: ["javascriptreact"]
}, {
name: "TypeScript",
since: "1.4.0",
parsers: ["typescript-eslint"],
group: "JavaScript",
aliases: ["ts"],
extensions: [".ts", ".tsx"],
tmScope: "source.ts",
aceMode: "typescript",
codemirrorMode: "javascript",
codemirrorMimeType: "application/typescript",
liguistLanguageId: 378,
vscodeLanguageIds: ["typescript", "typescriptreact"]
}, {
name: "JSON.stringify",
since: "1.13.0",
parsers: ["json-stringify"],
group: "JavaScript",
tmScope: "source.json",
aceMode: "json",
codemirrorMode: "javascript",
codemirrorMimeType: "application/json",
extensions: [],
// .json file defaults to json instead of json-stringify
filenames: ["package.json", "package-lock.json", "composer.json"],
linguistLanguageId: 174,
vscodeLanguageIds: ["json"]
}, {
name: "JSON",
since: "1.5.0",
parsers: ["json"],
group: "JavaScript",
tmScope: "source.json",
aceMode: "json",
codemirrorMode: "javascript",
codemirrorMimeType: "application/json",
extensions: [".json", ".geojson", ".JSON-tmLanguage", ".topojson"],
filenames: [".arcconfig", ".jshintrc", ".eslintrc", ".prettierrc", "composer.lock", "mcmod.info"],
linguistLanguageId: 174,
vscodeLanguageIds: ["json", "jsonc"]
}, {
name: "JSON5",
since: "1.13.0",
parsers: ["json5"],
group: "JavaScript",
tmScope: "source.json",
aceMode: "json",
codemirrorMode: "javascript",
codemirrorMimeType: "application/json",
extensions: [".json5"],
filenames: [".babelrc"],
linguistLanguageId: 175,
vscodeLanguageIds: ["json5"]
}];
var printers = {
estree: printerEstree,
"estree-json": printerEstreeJson
};
var languageJs = {
languages,
options: options$4,
printers
};
var index$5 = ["a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp"];
var htmlTagNames = Object.freeze({
default: index$5
});
var htmlTagNames$1 = ( htmlTagNames && index$5 ) || htmlTagNames;
function clean$3(ast, newObj) {
["raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) {
delete newObj[name];
});
if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
delete newObj.value;
}
if (ast.type === "css-rule") {
delete newObj.params;
}
if (ast.type === "selector-combinator") {
newObj.value = newObj.value.replace(/\s+/g, " ");
}
if (ast.type === "media-feature") {
newObj.value = newObj.value.replace(/ /g, "");
}
if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
newObj.value = newObj.value.toLowerCase();
}
if (ast.type === "css-decl") {
newObj.prop = newObj.prop.toLowerCase();
}
if (ast.type === "css-atrule" || ast.type === "css-import") {
newObj.name = newObj.name.toLowerCase();
}
if (ast.type === "value-number") {
newObj.unit = newObj.unit.toLowerCase();
}
if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) {
newObj.value = cleanCSSStrings(newObj.value);
}
if (ast.type === "selector-attribute") {
newObj.attribute = newObj.attribute.trim();
if (newObj.namespace) {
if (typeof newObj.namespace === "string") {
newObj.namespace = newObj.namespace.trim();
if (newObj.namespace.length === 0) {
newObj.namespace = true;
}
}
}
if (newObj.value) {
newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
delete newObj.quoted;
}
}
if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) {
newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) {
var num = Number(numStr);
return isNaN(num) ? match : num + unit.toLowerCase();
});
}
if (ast.type === "selector-tag") {
var lowercasedValue = ast.value.toLowerCase();
if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) {
newObj.value = lowercasedValue;
}
if (["from", "to"].indexOf(lowercasedValue) !== -1) {
newObj.value = lowercasedValue;
}
} // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
delete newObj.value;
} // Workaround for SCSS nested properties
if (ast.type === "selector-unknown") {
delete newObj.value;
}
}
function cleanCSSStrings(value) {
return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
}
var clean_1$2 = clean$3;
var colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"];
function getAncestorCounter(path$$1, typeOrTypes) {
var types = [].concat(typeOrTypes);
var counter = -1;
var ancestorNode;
while (ancestorNode = path$$1.getParentNode(++counter)) {
if (types.indexOf(ancestorNode.type) !== -1) {
return counter;
}
}
return -1;
}
function getAncestorNode$1(path$$1, typeOrTypes) {
var counter = getAncestorCounter(path$$1, typeOrTypes);
return counter === -1 ? null : path$$1.getParentNode(counter);
}
function getPropOfDeclNode$1(path$$1) {
var declAncestorNode = getAncestorNode$1(path$$1, "css-decl");
return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
}
function isSCSS$1(parser, text) {
var hasExplicitParserChoice = parser === "less" || parser === "scss";
var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/;
return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
}
function isWideKeywords$1(value) {
return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1;
}
function isKeyframeAtRuleKeywords$1(path$$1, value) {
var atRuleAncestorNode = getAncestorNode$1(path$$1, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1;
}
function maybeToLowerCase$1(value) {
return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
}
function insideValueFunctionNode$1(path$$1, functionName) {
var funcAncestorNode = getAncestorNode$1(path$$1, "value-func");
return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
}
function insideICSSRuleNode$1(path$$1) {
var ruleAncestorNode = getAncestorNode$1(path$$1, "css-rule");
return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
}
function insideAtRuleNode$1(path$$1, atRuleNameOrAtRuleNames) {
var atRuleNames = [].concat(atRuleNameOrAtRuleNames);
var atRuleAncestorNode = getAncestorNode$1(path$$1, "css-atrule");
return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1;
}
function insideURLFunctionInImportAtRuleNode$1(path$$1) {
var node = path$$1.getValue();
var atRuleAncestorNode = getAncestorNode$1(path$$1, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
}
function isURLFunctionNode$1(node) {
return node.type === "value-func" && node.value.toLowerCase() === "url";
}
function isLastNode$1(path$$1, node) {
var parentNode = path$$1.getParentNode();
if (!parentNode) {
return false;
}
var nodes = parentNode.nodes;
return nodes && nodes.indexOf(node) === nodes.length - 1;
}
function isHTMLTag$1(value) {
return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1;
}
function isDetachedRulesetDeclarationNode$1(node) {
// If a Less file ends up being parsed with the SCSS parser, Less
// variable declarations will be parsed as atrules with names ending
// with a colon, so keep the original case then.
if (!node.selector) {
return false;
}
return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
}
function isForKeywordNode$1(node) {
return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1;
}
function isIfElseKeywordNode$1(node) {
return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1;
}
function isEachKeywordNode$1(node) {
return node.type === "value-word" && node.value === "in";
}
function isMultiplicationNode$1(node) {
return node.type === "value-operator" && node.value === "*";
}
function isDivisionNode$1(node) {
return node.type === "value-operator" && node.value === "/";
}
function isAdditionNode$1(node) {
return node.type === "value-operator" && node.value === "+";
}
function isSubtractionNode$1(node) {
return node.type === "value-operator" && node.value === "-";
}
function isModuloNode(node) {
return node.type === "value-operator" && node.value === "%";
}
function isMathOperatorNode$1(node) {
return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node);
}
function isEqualityOperatorNode$1(node) {
return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1;
}
function isRelationalOperatorNode$1(node) {
return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1;
}
function isSCSSControlDirectiveNode$1(node) {
return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1;
}
function isSCSSNestedPropertyNode(node) {
if (!node.selector) {
return false;
}
return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
}
function isDetachedRulesetCallNode$1(node) {
return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
}
function isPostcssSimpleVarNode$1(currentNode, nextNode) {
return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
}
function hasComposesNode$1(node) {
return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
}
function hasParensAroundNode$1(node) {
return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null;
}
function hasEmptyRawBefore$1(node) {
return node.raws && node.raws.before === "";
}
function isKeyValuePairNode$1(node) {
return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
}
function isKeyValuePairInParenGroupNode(node) {
return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]);
}
function isSCSSMapItemNode$1(path$$1) {
var node = path$$1.getValue(); // Ignore empty item (i.e. `$key: ()`)
if (node.groups.length === 0) {
return false;
}
var parentParentNode = path$$1.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
return false;
}
var declNode = getAncestorNode$1(path$$1, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
return true;
} // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
if (isKeyValuePairInParenGroupNode(parentParentNode)) {
return true;
} // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
if (parentParentNode.type === "value-func") {
return true;
}
return false;
}
function isInlineValueCommentNode$1(node) {
return node.type === "value-comment" && node.inline;
}
function isHashNode$1(node) {
return node.type === "value-word" && node.value === "#";
}
function isLeftCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "{";
}
function isRightCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "}";
}
function isWordNode$1(node) {
return ["value-word", "value-atword"].indexOf(node.type) !== -1;
}
function isColonNode$1(node) {
return node.type === "value-colon";
}
function isMediaAndSupportsKeywords$1(node) {
return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1;
}
function isColorAdjusterFuncNode$1(node) {
if (node.type !== "value-func") {
return false;
}
return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1;
}
var utils$4 = {
getAncestorCounter,
getAncestorNode: getAncestorNode$1,
getPropOfDeclNode: getPropOfDeclNode$1,
maybeToLowerCase: maybeToLowerCase$1,
insideValueFunctionNode: insideValueFunctionNode$1,
insideICSSRuleNode: insideICSSRuleNode$1,
insideAtRuleNode: insideAtRuleNode$1,
insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
isHTMLTag: isHTMLTag$1,
isWideKeywords: isWideKeywords$1,
isSCSS: isSCSS$1,
isLastNode: isLastNode$1,
isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
isRelationalOperatorNode: isRelationalOperatorNode$1,
isEqualityOperatorNode: isEqualityOperatorNode$1,
isMultiplicationNode: isMultiplicationNode$1,
isDivisionNode: isDivisionNode$1,
isAdditionNode: isAdditionNode$1,
isSubtractionNode: isSubtractionNode$1,
isModuloNode,
isMathOperatorNode: isMathOperatorNode$1,
isEachKeywordNode: isEachKeywordNode$1,
isForKeywordNode: isForKeywordNode$1,
isURLFunctionNode: isURLFunctionNode$1,
isIfElseKeywordNode: isIfElseKeywordNode$1,
hasComposesNode: hasComposesNode$1,
hasParensAroundNode: hasParensAroundNode$1,
hasEmptyRawBefore: hasEmptyRawBefore$1,
isSCSSNestedPropertyNode,
isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
isKeyValuePairNode: isKeyValuePairNode$1,
isKeyValuePairInParenGroupNode,
isSCSSMapItemNode: isSCSSMapItemNode$1,
isInlineValueCommentNode: isInlineValueCommentNode$1,
isHashNode: isHashNode$1,
isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
isRightCurlyBraceNode: isRightCurlyBraceNode$1,
isWordNode: isWordNode$1,
isColonNode: isColonNode$1,
isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
isColorAdjusterFuncNode: isColorAdjusterFuncNode$1
};
var printNumber$2 = util$1.printNumber;
var printString$2 = util$1.printString;
var hasIgnoreComment$2 = util$1.hasIgnoreComment;
var hasNewline$3 = util$1.hasNewline;
var isNextLineEmpty$3 = utilShared.isNextLineEmpty;
var _require$$2$builders = doc.builders;
var concat$7 = _require$$2$builders.concat;
var join$5 = _require$$2$builders.join;
var line$4 = _require$$2$builders.line;
var hardline$6 = _require$$2$builders.hardline;
var softline$3 = _require$$2$builders.softline;
var group$2 = _require$$2$builders.group;
var fill$3 = _require$$2$builders.fill;
var indent$5 = _require$$2$builders.indent;
var dedent$3 = _require$$2$builders.dedent;
var ifBreak$2 = _require$$2$builders.ifBreak;
var removeLines$2 = doc.utils.removeLines;
var getAncestorNode = utils$4.getAncestorNode;
var getPropOfDeclNode = utils$4.getPropOfDeclNode;
var maybeToLowerCase = utils$4.maybeToLowerCase;
var insideValueFunctionNode = utils$4.insideValueFunctionNode;
var insideICSSRuleNode = utils$4.insideICSSRuleNode;
var insideAtRuleNode = utils$4.insideAtRuleNode;
var insideURLFunctionInImportAtRuleNode = utils$4.insideURLFunctionInImportAtRuleNode;
var isKeyframeAtRuleKeywords = utils$4.isKeyframeAtRuleKeywords;
var isHTMLTag = utils$4.isHTMLTag;
var isWideKeywords = utils$4.isWideKeywords;
var isSCSS = utils$4.isSCSS;
var isLastNode = utils$4.isLastNode;
var isSCSSControlDirectiveNode = utils$4.isSCSSControlDirectiveNode;
var isDetachedRulesetDeclarationNode = utils$4.isDetachedRulesetDeclarationNode;
var isRelationalOperatorNode = utils$4.isRelationalOperatorNode;
var isEqualityOperatorNode = utils$4.isEqualityOperatorNode;
var isMultiplicationNode = utils$4.isMultiplicationNode;
var isDivisionNode = utils$4.isDivisionNode;
var isAdditionNode = utils$4.isAdditionNode;
var isSubtractionNode = utils$4.isSubtractionNode;
var isMathOperatorNode = utils$4.isMathOperatorNode;
var isEachKeywordNode = utils$4.isEachKeywordNode;
var isForKeywordNode = utils$4.isForKeywordNode;
var isURLFunctionNode = utils$4.isURLFunctionNode;
var isIfElseKeywordNode = utils$4.isIfElseKeywordNode;
var hasComposesNode = utils$4.hasComposesNode;
var hasParensAroundNode = utils$4.hasParensAroundNode;
var hasEmptyRawBefore = utils$4.hasEmptyRawBefore;
var isKeyValuePairNode = utils$4.isKeyValuePairNode;
var isDetachedRulesetCallNode = utils$4.isDetachedRulesetCallNode;
var isPostcssSimpleVarNode = utils$4.isPostcssSimpleVarNode;
var isSCSSMapItemNode = utils$4.isSCSSMapItemNode;
var isInlineValueCommentNode = utils$4.isInlineValueCommentNode;
var isHashNode = utils$4.isHashNode;
var isLeftCurlyBraceNode = utils$4.isLeftCurlyBraceNode;
var isRightCurlyBraceNode = utils$4.isRightCurlyBraceNode;
var isWordNode = utils$4.isWordNode;
var isColonNode = utils$4.isColonNode;
var isMediaAndSupportsKeywords = utils$4.isMediaAndSupportsKeywords;
var isColorAdjusterFuncNode = utils$4.isColorAdjusterFuncNode;
function shouldPrintComma$1(options) {
switch (options.trailingComma) {
case "all":
case "es5":
return true;
case "none":
default:
return false;
}
}
function genericPrint$3(path$$1, options, print) {
var node = path$$1.getValue();
/* istanbul ignore if */
if (!node) {
return "";
}
if (typeof node === "string") {
return node;
}
switch (node.type) {
case "front-matter":
return concat$7([node.value, hardline$6]);
case "css-root":
{
var nodes = printNodeSequence(path$$1, options, print);
if (nodes.parts.length) {
return concat$7([nodes, hardline$6]);
}
return nodes;
}
case "css-comment":
{
if (node.raws.content) {
return node.raws.content;
}
var text = options.originalText.slice(options.locStart(node), options.locEnd(node));
var rawText = node.raws.text || node.text; // Workaround a bug where the location is off.
// https://github.com/postcss/postcss-scss/issues/63
if (text.indexOf(rawText) === -1) {
if (node.raws.inline) {
return concat$7(["// ", rawText]);
}
return concat$7(["/* ", rawText, " */"]);
}
return text;
}
case "css-rule":
{
return concat$7([path$$1.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$7([" {", node.nodes.length > 0 ? indent$5(concat$7([hardline$6, printNodeSequence(path$$1, options, print)])) : "", hardline$6, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""]) : ";"]);
}
case "css-decl":
{
return concat$7([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path$$1) ? node.prop : maybeToLowerCase(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode(node) ? removeLines$2(path$$1.call(print, "value")) : path$$1.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$7([" {", indent$5(concat$7([softline$3, printNodeSequence(path$$1, options, print)])), softline$3, "}"]) : ";"]);
}
case "css-atrule":
{
return concat$7(["@", // If a Less file ends up being parsed with the SCSS parser, Less
// variable declarations will be parsed as at-rules with names ending
// with a colon, so keep the original case then.
isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? concat$7([isDetachedRulesetCallNode(node) ? "" : " ", path$$1.call(print, "params")]) : "", node.selector ? indent$5(concat$7([" ", path$$1.call(print, "selector")])) : "", node.value ? group$2(concat$7([" ", path$$1.call(print, "value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$4 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$7([isSCSSControlDirectiveNode(node) ? "" : " ", "{", indent$5(concat$7([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path$$1, options, print)])), softline$3, "}"]) : ";"]);
}
// postcss-media-query-parser
case "media-query-list":
{
var parts = [];
path$$1.each(function (childPath) {
var node = childPath.getValue();
if (node.type === "media-query" && node.value === "") {
return;
}
parts.push(childPath.call(print));
}, "nodes");
return group$2(indent$5(join$5(line$4, parts)));
}
case "media-query":
{
return concat$7([join$5(" ", path$$1.map(print, "nodes")), isLastNode(path$$1, node) ? "" : ","]);
}
case "media-type":
{
return adjustNumbers(adjustStrings(node.value, options));
}
case "media-feature-expression":
{
if (!node.nodes) {
return node.value;
}
return concat$7(["(", concat$7(path$$1.map(print, "nodes")), ")"]);
}
case "media-feature":
{
return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options));
}
case "media-colon":
{
return concat$7([node.value, " "]);
}
case "media-value":
{
return adjustNumbers(adjustStrings(node.value, options));
}
case "media-keyword":
{
return adjustStrings(node.value, options);
}
case "media-url":
{
return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
}
case "media-unknown":
{
return node.value;
}
// postcss-selector-parser
case "selector-root":
{
return group$2(concat$7([insideAtRuleNode(path$$1, "custom-selector") ? concat$7([getAncestorNode(path$$1, "css-atrule").customSelector, line$4]) : "", join$5(concat$7([",", insideAtRuleNode(path$$1, ["extend", "custom-selector", "nest"]) ? line$4 : hardline$6]), path$$1.map(print, "nodes"))]));
}
case "selector-selector":
{
return group$2(indent$5(concat$7(path$$1.map(print, "nodes"))));
}
case "selector-comment":
{
return node.value;
}
case "selector-string":
{
return adjustStrings(node.value, options);
}
case "selector-tag":
{
var parentNode = path$$1.getParentNode();
var index = parentNode && parentNode.nodes.indexOf(node);
var prevNode = index && parentNode.nodes[index - 1];
return concat$7([node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag(node.value) || isKeyframeAtRuleKeywords(path$$1, node.value) ? node.value.toLowerCase() : node.value)]);
}
case "selector-id":
{
return concat$7(["#", node.value]);
}
case "selector-class":
{
return concat$7([".", adjustNumbers(adjustStrings(node.value, options))]);
}
case "selector-attribute":
{
return concat$7(["[", node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
}
case "selector-combinator":
{
if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
var _parentNode = path$$1.getParentNode();
var _leading = _parentNode.type === "selector-selector" && _parentNode.nodes[0] === node ? "" : line$4;
return concat$7([_leading, node.value, isLastNode(path$$1, node) ? "" : " "]);
}
var leading = node.value.trim().startsWith("(") ? line$4 : "";
var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$4;
return concat$7([leading, value]);
}
case "selector-universal":
{
return concat$7([node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", adjustNumbers(node.value)]);
}
case "selector-pseudo":
{
return concat$7([maybeToLowerCase(node.value), node.nodes && node.nodes.length > 0 ? concat$7(["(", join$5(", ", path$$1.map(print, "nodes")), ")"]) : ""]);
}
case "selector-nesting":
{
return node.value;
}
case "selector-unknown":
{
var ruleAncestorNode = getAncestorNode(path$$1, "css-rule"); // Nested SCSS property
if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options));
}
return node.value;
}
// postcss-values-parser
case "value-value":
case "value-root":
{
return path$$1.call(print, "group");
}
case "value-comment":
{
return concat$7([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]);
}
case "value-comma_group":
{
var _parentNode2 = path$$1.getParentNode();
var parentParentNode = path$$1.getParentNode(1);
var declAncestorProp = getPropOfDeclNode(path$$1);
var isGridValue = declAncestorProp && _parentNode2.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
var atRuleAncestorNode = getAncestorNode(path$$1, "css-atrule");
var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode);
var printed = path$$1.map(print, "groups");
var _parts = [];
var insideURLFunction = insideValueFunctionNode(path$$1, "url");
var insideSCSSInterpolationInString = false;
var didBreak = false;
for (var i = 0; i < node.groups.length; ++i) {
_parts.push(printed[i]); // Ignore value inside `url()`
if (insideURLFunction) {
continue;
}
var iPrevNode = node.groups[i - 1];
var iNode = node.groups[i];
var iNextNode = node.groups[i + 1];
var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon)
if (!iNextNode) {
continue;
} // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
var isStartSCSSinterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
var isEndingSCSSinterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
if (isStartSCSSinterpolationInString || isEndingSCSSinterpolationInString) {
insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
continue;
}
if (insideSCSSInterpolationInString) {
continue;
} // Ignore colon (i.e. `:`)
if (isColonNode(iNode) || isColonNode(iNextNode)) {
continue;
} // Ignore `@` in Less (i.e. `@@var;`)
if (iNode.type === "value-atword" && iNode.value === "") {
continue;
} // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
if (iNode.value === "~") {
continue;
} // Ignore `\` (i.e. `$variable: \@small;`)
if (iNode.value === "\\") {
continue;
} // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
if (isPostcssSimpleVarNode(iNode, iNextNode)) {
continue;
} // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
if (iNode.value === "--" && isHashNode(iNextNode)) {
continue;
} // Formatting math operations
var isMathOperator = isMathOperatorNode(iNode);
var isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
// (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
// (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Print spaces before and after addition and subtraction math operators as is in `calc` function
// due to the fact that it is not valid syntax
// (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
if (insideValueFunctionNode(path$$1, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
// Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
var isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode);
var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode);
var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign
if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path$$1, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) {
continue;
} // Ignore inline comment, they already contain newline at end (i.e. `// Comment`)
// Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
var isInlineComment = isInlineValueCommentNode(iNode);
if (iPrevNode && isInlineValueCommentNode(iPrevNode) || isInlineComment || isInlineValueCommentNode(iNextNode)) {
if (isInlineComment) {
_parts.push(hardline$6);
}
continue;
} // Handle keywords in SCSS control directive
if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) {
_parts.push(" ");
continue;
} // At-rule `namespace` should be in one line
if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
_parts.push(" ");
continue;
} // Formatting `grid` property
if (isGridValue) {
if (iNode.source.start.line !== iNextNode.source.start.line) {
_parts.push(hardline$6);
didBreak = true;
} else {
_parts.push(" ");
}
continue;
} // Add `space` before next math operation
// Note: `grip` property have `/` delimiter and it is not math operation, so
// `grid` property handles above
if (isNextMathOperator) {
_parts.push(" ");
continue;
} // Be default all values go through `line`
_parts.push(line$4);
}
if (didBreak) {
_parts.unshift(hardline$6);
}
if (isControlDirective) {
return group$2(indent$5(concat$7(_parts)));
} // Indent is not needed for import url when url is very long
// and node has two groups
// when type is value-comma_group
// example @import url("verylongurl") projection,tv
if (insideURLFunctionInImportAtRuleNode(path$$1)) {
return group$2(fill$3(_parts));
}
return group$2(indent$5(fill$3(_parts)));
}
case "value-paren_group":
{
var _parentNode3 = path$$1.getParentNode();
if (_parentNode3 && isURLFunctionNode(_parentNode3) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) {
return concat$7([node.open ? path$$1.call(print, "open") : "", join$5(",", path$$1.map(print, "groups")), node.close ? path$$1.call(print, "close") : ""]);
}
if (!node.open) {
var _printed = path$$1.map(print, "groups");
var res = [];
for (var _i = 0; _i < _printed.length; _i++) {
if (_i !== 0) {
res.push(concat$7([",", line$4]));
}
res.push(_printed[_i]);
}
return group$2(indent$5(fill$3(res)));
}
var isSCSSMapItem = isSCSSMapItemNode(path$$1);
return group$2(concat$7([node.open ? path$$1.call(print, "open") : "", indent$5(concat$7([softline$3, join$5(concat$7([",", line$4]), path$$1.map(function (childPath) {
var node = childPath.getValue();
var printed = print(childPath); // Key/Value pair in open paren already indented
if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
printed.contents.contents.parts[1] = group$2(printed.contents.contents.parts[1]);
return group$2(dedent$3(printed));
}
return printed;
}, "groups"))])), ifBreak$2(isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path$$1.call(print, "close") : ""]), {
shouldBreak: isSCSSMapItem
});
}
case "value-func":
{
return concat$7([node.value, insideAtRuleNode(path$$1, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", path$$1.call(print, "group")]);
}
case "value-paren":
{
return node.value;
}
case "value-number":
{
return concat$7([printCssNumber(node.value), maybeToLowerCase(node.unit)]);
}
case "value-operator":
{
return node.value;
}
case "value-word":
{
if (node.isColor && node.isHex || isWideKeywords(node.value)) {
return node.value.toLowerCase();
}
return node.value;
}
case "value-colon":
{
return concat$7([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
insideValueFunctionNode(path$$1, "url") ? "" : line$4]);
}
case "value-comma":
{
return concat$7([node.value, " "]);
}
case "value-string":
{
return printString$2(node.raws.quote + node.value + node.raws.quote, options);
}
case "value-atword":
{
return concat$7(["@", node.value]);
}
case "value-unicode-range":
{
return node.value;
}
case "value-unknown":
{
return node.value;
}
default:
/* istanbul ignore next */
throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
}
}
function printNodeSequence(path$$1, options, print) {
var node = path$$1.getValue();
var parts = [];
var i = 0;
path$$1.map(function (pathChild) {
var prevNode = node.nodes[i - 1];
if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
var childNode = pathChild.getValue();
parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
} else {
parts.push(pathChild.call(print));
}
if (i !== node.nodes.length - 1) {
if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), {
backwards: true
}) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
parts.push(" ");
} else {
parts.push(hardline$6);
if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options)) {
parts.push(hardline$6);
}
}
}
i++;
}, "nodes");
return concat$7(parts);
}
var STRING_REGEX = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX.source + `|` + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
function adjustStrings(value, options) {
return value.replace(STRING_REGEX, function (match) {
return printString$2(match, options);
});
}
function quoteAttributeValue(value, options) {
var quote = options.singleQuote ? "'" : '"';
return value.includes('"') || value.includes("'") ? value : quote + value + quote;
}
function adjustNumbers(value) {
return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) {
return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase(unit || "") : match;
});
}
function printCssNumber(rawNumber) {
return printNumber$2(rawNumber) // Remove trailing `.0`.
.replace(/\.0(?=$|e)/, "");
}
var printerPostcss = {
print: genericPrint$3,
hasPrettierIgnore: hasIgnoreComment$2,
massageAstNode: clean_1$2
};
var options$7 = {
singleQuote: commonOptions.singleQuote
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$1 = [{
name: "CSS",
since: "1.4.0",
parsers: ["css"],
group: "CSS",
tmScope: "source.css",
aceMode: "css",
codemirrorMode: "css",
codemirrorMimeType: "text/css",
extensions: [".css", ".pcss", ".postcss"],
liguistLanguageId: 50,
vscodeLanguageIds: ["css", "postcss"]
}, {
name: "Less",
since: "1.4.0",
parsers: ["less"],
group: "CSS",
extensions: [".less"],
tmScope: "source.css.less",
aceMode: "less",
codemirrorMode: "css",
codemirrorMimeType: "text/css",
liguistLanguageId: 198,
vscodeLanguageIds: ["less"]
}, {
name: "SCSS",
since: "1.4.0",
parsers: ["scss"],
group: "CSS",
tmScope: "source.scss",
aceMode: "scss",
codemirrorMode: "css",
codemirrorMimeType: "text/x-scss",
extensions: [".scss"],
liguistLanguageId: 329,
vscodeLanguageIds: ["scss"]
}];
var printers$1 = {
postcss: printerPostcss
};
var languageCss = {
languages: languages$1,
options: options$7,
printers: printers$1
};
var _require$$0$builders$3 = doc.builders;
var concat$8 = _require$$0$builders$3.concat;
var join$6 = _require$$0$builders$3.join;
var softline$4 = _require$$0$builders$3.softline;
var hardline$7 = _require$$0$builders$3.hardline;
var line$5 = _require$$0$builders$3.line;
var group$3 = _require$$0$builders$3.group;
var indent$6 = _require$$0$builders$3.indent;
var ifBreak$3 = _require$$0$builders$3.ifBreak; // http://w3c.github.io/html/single-page.html#void-elements
var voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter:
// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
function print(path$$1, options, print) {
var n = path$$1.getValue();
/* istanbul ignore if*/
if (!n) {
return "";
}
switch (n.type) {
case "Program":
{
return group$3(join$6(softline$4, path$$1.map(print, "body").filter(function (text) {
return text !== "";
})));
}
case "ElementNode":
{
var isVoid = voidTags.indexOf(n.tag) !== -1;
var closeTag = isVoid ? concat$8([" />", softline$4]) : ">";
var hasChildren = n.children.length > 0;
var _getParams = function _getParams(path$$1, print) {
return indent$6(concat$8([n.attributes.length ? line$5 : "", join$6(line$5, path$$1.map(print, "attributes")), n.modifiers.length ? line$5 : "", join$6(line$5, path$$1.map(print, "modifiers")), n.comments.length ? line$5 : "", join$6(line$5, path$$1.map(print, "comments"))]));
}; // The problem here is that I want to not break at all if the children
// would not break but I need to force an indent, so I use a hardline.
/**
* What happens now:
*
* Hello
*
* ==>
*
Hello
* This is due to me using hasChildren to decide to put the hardline in.
* I would rather use a {DOES THE WHOLE THING NEED TO BREAK}
*/
return concat$8([group$3(concat$8(["<", n.tag, _getParams(path$$1, print), ifBreak$3(softline$4, ""), closeTag])), group$3(concat$8([indent$6(join$6(softline$4, [""].concat(path$$1.map(print, "children")))), ifBreak$3(hasChildren ? hardline$7 : "", ""), !isVoid ? concat$8(["", n.tag, ">"]) : ""]))]);
}
case "BlockStatement":
{
var pp = path$$1.getParentNode(1);
var isElseIf = pp && pp.inverse && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
var hasElseIf = n.inverse && n.inverse.body[0] && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
var indentElse = hasElseIf ? function (a) {
return a;
} : indent$6;
if (n.inverse) {
return concat$8([isElseIf ? concat$8(["{{else ", printPathParams(path$$1, print), "}}"]) : printOpenBlock(path$$1, print), indent$6(concat$8([hardline$7, path$$1.call(print, "program")])), n.inverse && !hasElseIf ? concat$8([hardline$7, "{{else}}"]) : "", n.inverse ? indentElse(concat$8([hardline$7, path$$1.call(print, "inverse")])) : "", isElseIf ? "" : concat$8([hardline$7, printCloseBlock(path$$1, print)])]);
} else if (isElseIf) {
return concat$8([concat$8(["{{else ", printPathParams(path$$1, print), "}}"]), indent$6(concat$8([hardline$7, path$$1.call(print, "program")]))]);
}
/**
* I want this boolean to be: if params are going to cause a break,
* not that it has params.
*/
var hasParams = n.params.length > 0 || n.hash.pairs.length > 0;
var _hasChildren = n.program.body.length > 0;
return concat$8([printOpenBlock(path$$1, print), group$3(concat$8([indent$6(concat$8([softline$4, path$$1.call(print, "program")])), hasParams && _hasChildren ? hardline$7 : "", printCloseBlock(path$$1, print)]))]);
}
case "ElementModifierStatement":
case "MustacheStatement":
{
var _pp = path$$1.getParentNode(1);
var isConcat = _pp && _pp.type === "ConcatStatement";
return group$3(concat$8([n.escaped === false ? "{{{" : "{{", printPathParams(path$$1, print), isConcat ? "" : softline$4, n.escaped === false ? "}}}" : "}}"]));
}
case "SubExpression":
{
return group$3(concat$8(["(", printPath(path$$1, print), indent$6(concat$8([line$5, group$3(join$6(line$5, getParams(path$$1, print)))])), softline$4, ")"]));
}
case "AttrNode":
{
var quote = n.value.type === "TextNode" ? '"' : "";
return concat$8([n.name, "=", quote, path$$1.call(print, "value"), quote]);
}
case "ConcatStatement":
{
return concat$8(['"', group$3(indent$6(join$6(softline$4, path$$1.map(function (partPath) {
return print(partPath);
}, "parts").filter(function (a) {
return a !== "";
})))), '"']);
}
case "Hash":
{
return concat$8([join$6(line$5, path$$1.map(print, "pairs"))]);
}
case "HashPair":
{
return concat$8([n.key, "=", path$$1.call(print, "value")]);
}
case "TextNode":
{
var leadingSpace = "";
var trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present, when next to mustache statement.
var inAttrNode = path$$1.stack.indexOf("attributes") >= 0;
if (inAttrNode) {
var parentNode = path$$1.getParentNode(0);
var _isConcat = parentNode.type === "ConcatStatement";
if (_isConcat) {
var parts = parentNode.parts;
var partIndex = parts.indexOf(n);
if (partIndex > 0) {
var partType = parts[partIndex - 1].type;
var isMustache = partType === "MustacheStatement";
if (isMustache) {
leadingSpace = " ";
}
}
if (partIndex < parts.length - 1) {
var _partType = parts[partIndex + 1].type;
var _isMustache = _partType === "MustacheStatement";
if (_isMustache) {
trailingSpace = " ";
}
}
}
}
return n.chars.replace(/^\s+/, leadingSpace).replace(/\s+$/, trailingSpace);
}
case "MustacheCommentStatement":
{
var dashes = n.value.indexOf("}}") > -1 ? "--" : "";
return concat$8(["{{!", dashes, n.value, dashes, "}}"]);
}
case "PathExpression":
{
return n.original;
}
case "BooleanLiteral":
{
return String(n.value);
}
case "CommentStatement":
{
return concat$8([""]);
}
case "StringLiteral":
{
return `"${n.value}"`;
}
case "NumberLiteral":
{
return String(n.value);
}
case "UndefinedLiteral":
{
return "undefined";
}
case "NullLiteral":
{
return "null";
}
/* istanbul ignore next */
default:
throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
}
}
function printPath(path$$1, print) {
return path$$1.call(print, "path");
}
function getParams(path$$1, print) {
var node = path$$1.getValue();
var parts = [];
if (node.params.length > 0) {
parts = parts.concat(path$$1.map(print, "params"));
}
if (node.hash && node.hash.pairs.length > 0) {
parts.push(path$$1.call(print, "hash"));
}
return parts;
}
function printPathParams(path$$1, print) {
var parts = [];
parts.push(printPath(path$$1, print));
parts = parts.concat(getParams(path$$1, print));
return indent$6(group$3(join$6(line$5, parts)));
}
function printBlockParams(path$$1) {
var block = path$$1.getValue();
if (!block.program || !block.program.blockParams.length) {
return "";
}
return concat$8([" as |", block.program.blockParams.join(" "), "|"]);
}
function printOpenBlock(path$$1, print) {
return group$3(concat$8(["{{#", printPathParams(path$$1, print), printBlockParams(path$$1, print), softline$4, "}}"]));
}
function printCloseBlock(path$$1, print) {
return concat$8(["{{/", path$$1.call(print, "path"), "}}"]);
}
function clean$5(ast, newObj) {
delete newObj.loc; // (Glimmer/HTML) ignore TextNode whitespace
if (ast.type === "TextNode") {
if (ast.chars.replace(/\s+/, "") === "") {
return null;
}
newObj.chars = ast.chars.replace(/^\s+/, "").replace(/\s+$/, "");
}
}
var printerGlimmer = {
print,
massageAstNode: clean$5
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$2 = [{
type: "markup",
group: "HTML",
aliases: ["hbs", "htmlbars"],
extensions: [".handlebars", ".hbs"],
tm_scope: "text.html.handlebars",
ace_mode: "handlebars",
language_id: 155,
since: null // unreleased
}];
var printers$2 = {
glimmer: printerGlimmer
};
var languageHandlebars = {
languages: languages$2,
printers: printers$2
};
var _require$$0$builders$4 = doc.builders;
var concat$9 = _require$$0$builders$4.concat;
var join$7 = _require$$0$builders$4.join;
var hardline$8 = _require$$0$builders$4.hardline;
var line$6 = _require$$0$builders$4.line;
var softline$5 = _require$$0$builders$4.softline;
var group$4 = _require$$0$builders$4.group;
var indent$7 = _require$$0$builders$4.indent;
var ifBreak$4 = _require$$0$builders$4.ifBreak;
var hasIgnoreComment$3 = util$1.hasIgnoreComment;
var isNextLineEmpty$4 = utilShared.isNextLineEmpty;
function genericPrint$4(path$$1, options, print) {
var n = path$$1.getValue();
if (!n) {
return "";
}
if (typeof n === "string") {
return n;
}
switch (n.kind) {
case "Document":
{
var parts = [];
path$$1.map(function (pathChild, index) {
parts.push(concat$9([pathChild.call(print)]));
if (index !== n.definitions.length - 1) {
parts.push(hardline$8);
if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options)) {
parts.push(hardline$8);
}
}
}, "definitions");
return concat$9([concat$9(parts), hardline$8]);
}
case "OperationDefinition":
{
var hasOperation = options.originalText[options.locStart(n)] !== "{";
var hasName = !!n.name;
return concat$9([hasOperation ? n.operation : "", hasOperation && hasName ? concat$9([" ", path$$1.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$4(concat$9(["(", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", printDirectives(path$$1, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path$$1.call(print, "selectionSet")]);
}
case "FragmentDefinition":
{
return concat$9(["fragment ", path$$1.call(print, "name"), " on ", path$$1.call(print, "typeCondition"), printDirectives(path$$1, print, n), " ", path$$1.call(print, "selectionSet")]);
}
case "SelectionSet":
{
return concat$9(["{", indent$7(concat$9([hardline$8, join$7(hardline$8, path$$1.call(function (selectionsPath) {
return printSequence(selectionsPath, options, print);
}, "selections"))])), hardline$8, "}"]);
}
case "Field":
{
return group$4(concat$9([n.alias ? concat$9([path$$1.call(print, "alias"), ": "]) : "", path$$1.call(print, "name"), n.arguments.length > 0 ? group$4(concat$9(["(", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$5, ")"])) : "", printDirectives(path$$1, print, n), n.selectionSet ? " " : "", path$$1.call(print, "selectionSet")]));
}
case "Name":
{
return n.value;
}
case "StringValue":
{
if (n.block) {
return concat$9(['"""', hardline$8, join$7(hardline$8, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$8, '"""']);
}
return concat$9(['"', n.value.replace(/["\\]/g, "\\$&"), '"']);
}
case "IntValue":
case "FloatValue":
case "EnumValue":
{
return n.value;
}
case "BooleanValue":
{
return n.value ? "true" : "false";
}
case "NullValue":
{
return "null";
}
case "Variable":
{
return concat$9(["$", path$$1.call(print, "name")]);
}
case "ListValue":
{
return group$4(concat$9(["[", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.map(print, "values"))])), softline$5, "]"]));
}
case "ObjectValue":
{
return group$4(concat$9(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.map(print, "fields"))])), softline$5, ifBreak$4("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
}
case "ObjectField":
case "Argument":
{
return concat$9([path$$1.call(print, "name"), ": ", path$$1.call(print, "value")]);
}
case "Directive":
{
return concat$9(["@", path$$1.call(print, "name"), n.arguments.length > 0 ? group$4(concat$9(["(", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$5, ")"])) : ""]);
}
case "NamedType":
{
return path$$1.call(print, "name");
}
case "VariableDefinition":
{
return concat$9([path$$1.call(print, "variable"), ": ", path$$1.call(print, "type"), n.defaultValue ? concat$9([" = ", path$$1.call(print, "defaultValue")]) : ""]);
}
case "TypeExtensionDefinition":
{
return concat$9(["extend ", path$$1.call(print, "definition")]);
}
case "ObjectTypeExtension":
case "ObjectTypeDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path$$1.call(print, "name"), n.interfaces.length > 0 ? concat$9([" implements ", join$7(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path$$1.map(print, "interfaces"))]) : "", printDirectives(path$$1, print, n), n.fields.length > 0 ? concat$9([" {", indent$7(concat$9([hardline$8, join$7(hardline$8, path$$1.call(function (fieldsPath) {
return printSequence(fieldsPath, options, print);
}, "fields"))])), hardline$8, "}"]) : ""]);
}
case "FieldDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", path$$1.call(print, "name"), n.arguments.length > 0 ? group$4(concat$9(["(", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$5, ")"])) : "", ": ", path$$1.call(print, "type"), printDirectives(path$$1, print, n)]);
}
case "DirectiveDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", "directive ", "@", path$$1.call(print, "name"), n.arguments.length > 0 ? group$4(concat$9(["(", indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$5, ")"])) : "", concat$9([" on ", join$7(" | ", path$$1.map(print, "locations"))])]);
}
case "EnumTypeExtension":
case "EnumTypeDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.values.length > 0 ? concat$9([" {", indent$7(concat$9([hardline$8, join$7(hardline$8, path$$1.call(function (valuesPath) {
return printSequence(valuesPath, options, print);
}, "values"))])), hardline$8, "}"]) : ""]);
}
case "EnumValueDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", path$$1.call(print, "name"), printDirectives(path$$1, print, n)]);
}
case "InputValueDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? n.description.block ? hardline$8 : line$6 : "", path$$1.call(print, "name"), ": ", path$$1.call(print, "type"), n.defaultValue ? concat$9([" = ", path$$1.call(print, "defaultValue")]) : "", printDirectives(path$$1, print, n)]);
}
case "InputObjectTypeExtension":
case "InputObjectTypeDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.fields.length > 0 ? concat$9([" {", indent$7(concat$9([hardline$8, join$7(hardline$8, path$$1.call(function (fieldsPath) {
return printSequence(fieldsPath, options, print);
}, "fields"))])), hardline$8, "}"]) : ""]);
}
case "SchemaDefinition":
{
return concat$9(["schema", printDirectives(path$$1, print, n), " {", n.operationTypes.length > 0 ? indent$7(concat$9([hardline$8, join$7(hardline$8, path$$1.call(function (opsPath) {
return printSequence(opsPath, options, print);
}, "operationTypes"))])) : "", hardline$8, "}"]);
}
case "OperationTypeDefinition":
{
return concat$9([path$$1.call(print, "operation"), ": ", path$$1.call(print, "type")]);
}
case "InterfaceTypeExtension":
case "InterfaceTypeDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.fields.length > 0 ? concat$9([" {", indent$7(concat$9([hardline$8, join$7(hardline$8, path$$1.call(function (fieldsPath) {
return printSequence(fieldsPath, options, print);
}, "fields"))])), hardline$8, "}"]) : ""]);
}
case "FragmentSpread":
{
return concat$9(["...", path$$1.call(print, "name"), printDirectives(path$$1, print, n)]);
}
case "InlineFragment":
{
return concat$9(["...", n.typeCondition ? concat$9([" on ", path$$1.call(print, "typeCondition")]) : "", printDirectives(path$$1, print, n), " ", path$$1.call(print, "selectionSet")]);
}
case "UnionTypeExtension":
case "UnionTypeDefinition":
{
return group$4(concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", group$4(concat$9([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.types.length > 0 ? concat$9([" =", ifBreak$4("", " "), indent$7(concat$9([ifBreak$4(concat$9([line$6, " "])), join$7(concat$9([line$6, "| "]), path$$1.map(print, "types"))]))]) : ""]))]));
}
case "ScalarTypeExtension":
case "ScalarTypeDefinition":
{
return concat$9([path$$1.call(print, "description"), n.description ? hardline$8 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path$$1.call(print, "name"), printDirectives(path$$1, print, n)]);
}
case "NonNullType":
{
return concat$9([path$$1.call(print, "type"), "!"]);
}
case "ListType":
{
return concat$9(["[", path$$1.call(print, "type"), "]"]);
}
default:
/* istanbul ignore next */
throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
}
}
function printDirectives(path$$1, print, n) {
if (n.directives.length === 0) {
return "";
}
return concat$9([" ", group$4(indent$7(concat$9([softline$5, join$7(concat$9([ifBreak$4("", " "), softline$5]), path$$1.map(print, "directives"))])))]);
}
function printSequence(sequencePath, options, print) {
var count = sequencePath.getValue().length;
return sequencePath.map(function (path$$1, i) {
var printed = print(path$$1);
if (isNextLineEmpty$4(options.originalText, path$$1.getValue(), options) && i < count - 1) {
return concat$9([printed, hardline$8]);
}
return printed;
});
}
function canAttachComment$1(node) {
return node.kind && node.kind !== "Comment";
}
function printComment$2(commentPath) {
var comment = commentPath.getValue();
switch (comment.kind) {
case "Comment":
return "#" + comment.value.trimRight();
default:
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function determineInterfaceSeparator(originalSource) {
var start = originalSource.indexOf("implements");
if (start === -1) {
throw new Error("Must implement interfaces: " + originalSource);
}
var end = originalSource.indexOf("{");
if (end === -1) {
end = originalSource.length;
}
return originalSource.substr(start, end).includes("&") ? " & " : ", ";
}
function clean$6(node, newNode
/*, parent*/
) {
delete newNode.loc;
delete newNode.comments;
}
var printerGraphql = {
print: genericPrint$4,
massageAstNode: clean$6,
hasPrettierIgnore: hasIgnoreComment$3,
printComment: printComment$2,
canAttachComment: canAttachComment$1
};
var options$10 = {
bracketSpacing: commonOptions.bracketSpacing
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$3 = [{
name: "GraphQL",
since: "1.5.0",
parsers: ["graphql"],
extensions: [".graphql", ".gql"],
tmScope: "source.graphql",
aceMode: "text",
liguistLanguageId: 139,
vscodeLanguageIds: ["graphql"]
}];
var printers$3 = {
graphql: printerGraphql
};
var languageGraphql = {
languages: languages$3,
options: options$10,
printers: printers$3
};
var _require$$0$builders$6 = doc.builders;
var hardline$10 = _require$$0$builders$6.hardline;
var literalline$4 = _require$$0$builders$6.literalline;
var concat$11 = _require$$0$builders$6.concat;
var markAsRoot$2 = _require$$0$builders$6.markAsRoot;
var mapDoc$4 = doc.utils.mapDoc;
function embed$2(path$$1, print, textToDoc, options) {
var node = path$$1.getValue();
if (node.type === "code" && node.lang !== null) {
// only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
var lang = node.lang.split(/\s/, 1)[0];
var parser = getParserName(lang);
if (parser) {
var styleUnit = options.__inJsTemplate ? "~" : "`";
var style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
var doc$$2 = textToDoc(node.value, {
parser
});
return markAsRoot$2(concat$11([style, node.lang, hardline$10, replaceNewlinesWithLiterallines(doc$$2), style]));
}
}
return null;
function getParserName(lang) {
var supportInfo = support.getSupportInfo(null, {
plugins: options.plugins
});
var language = supportInfo.languages.find(function (language) {
return language.name.toLowerCase() === lang || language.extensions && language.extensions.find(function (ext) {
return ext.substring(1) === lang;
});
});
if (language) {
return language.parsers[0];
}
return null;
}
function replaceNewlinesWithLiterallines(doc$$2) {
return mapDoc$4(doc$$2, function (currentDoc) {
return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$11(currentDoc.split(/(\n)/g).map(function (v, i) {
return i % 2 === 0 ? v : literalline$4;
})) : currentDoc;
});
}
}
var embed_1$2 = embed$2;
function parse$5(text) {
var delimiter;
if (text.indexOf("---") === 0) {
delimiter = "---";
} else if (text.indexOf("+++") === 0) {
delimiter = "+++";
}
var end = -1;
if (!delimiter || (end = text.indexOf(`\n${delimiter}`, 3)) === -1) {
return {
frontMatter: null,
content: text
};
}
end = end + 4;
return {
frontMatter: text.slice(0, end),
content: text.slice(end)
};
}
var frontMatter = parse$5;
var pragma$2 = createCommonjsModule(function (module) {
"use strict";
var pragmas = ["format", "prettier"];
function startWithPragma(text) {
var pragma = `@(${pragmas.join("|")})`;
var regex = new RegExp([``, ``].join("|"), "m");
var matched = text.match(regex);
return matched && matched.index === 0;
}
module.exports = {
startWithPragma,
hasPragma: function hasPragma(text) {
return startWithPragma(frontMatter(text).content.trimLeft());
},
insertPragma: function insertPragma(text) {
var extracted = frontMatter(text);
var pragma = ``;
return extracted.frontMatter ? `${extracted.frontMatter}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
}
};
});
var _require$$0$builders$5 = doc.builders;
var concat$10 = _require$$0$builders$5.concat;
var join$8 = _require$$0$builders$5.join;
var line$7 = _require$$0$builders$5.line;
var literalline$3 = _require$$0$builders$5.literalline;
var markAsRoot$1 = _require$$0$builders$5.markAsRoot;
var hardline$9 = _require$$0$builders$5.hardline;
var softline$6 = _require$$0$builders$5.softline;
var fill$4 = _require$$0$builders$5.fill;
var align$2 = _require$$0$builders$5.align;
var indent$8 = _require$$0$builders$5.indent;
var group$5 = _require$$0$builders$5.group;
var mapDoc$3 = doc.utils.mapDoc;
var printDocToString$3 = doc.printer.printDocToString;
var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
var INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break"];
var INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
function genericPrint$5(path$$1, options, print) {
var node = path$$1.getValue();
if (shouldRemainTheSameContent(path$$1)) {
return concat$10(util$1.splitText(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) {
return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path$$1, node.value, options);
}));
}
switch (node.type) {
case "root":
if (node.children.length === 0) {
return "";
}
return concat$10([normalizeDoc(printRoot(path$$1, options, print)), hardline$9]);
case "paragraph":
return printChildren(path$$1, options, print, {
postprocessor: fill$4
});
case "sentence":
return printChildren(path$$1, options, print);
case "word":
return node.value.replace(/[*]/g, "\\*") // escape all `*`
.replace(new RegExp([`(^|[${util$1.punctuationCharRange}])(_+)`, `(_+)([${util$1.punctuationCharRange}]|$)`].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) {
return (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_");
});
// escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
case "whitespace":
{
var parentNode = path$$1.getParentNode();
var index = parentNode.children.indexOf(node);
var nextNode = parentNode.children[index + 1];
var proseWrap = // leading char that may cause different syntax
nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
return printLine(path$$1, node.value, {
proseWrap
});
}
case "emphasis":
{
var _parentNode = path$$1.getParentNode();
var _index = _parentNode.children.indexOf(node);
var prevNode = _parentNode.children[_index - 1];
var _nextNode = _parentNode.children[_index + 1];
var hasPrevOrNextWord = // `1*2*3` is considered emphais but `1_2_3` is not
prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || _nextNode && _nextNode.type === "sentence" && _nextNode.children.length > 0 && _nextNode.children[0].type === "word" && !_nextNode.children[0].hasLeadingPunctuation;
var style = hasPrevOrNextWord || getAncestorNode$2(path$$1, "emphasis") ? "*" : "_";
return concat$10([style, printChildren(path$$1, options, print), style]);
}
case "strong":
return concat$10(["**", printChildren(path$$1, options, print), "**"]);
case "delete":
return concat$10(["~~", printChildren(path$$1, options, print), "~~"]);
case "inlineCode":
{
var backtickCount = util$1.getMaxContinuousCount(node.value, "`");
var _style = backtickCount === 1 ? "``" : "`";
var gap = backtickCount ? " " : "";
return concat$10([_style, gap, node.value, gap, _style]);
}
case "link":
switch (options.originalText[node.position.start.offset]) {
case "<":
return concat$10(["<", node.url, ">"]);
case "[":
return concat$10(["[", printChildren(path$$1, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
default:
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
}
case "image":
return concat$10(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
case "blockquote":
return concat$10(["> ", align$2("> ", printChildren(path$$1, options, print))]);
case "heading":
return concat$10(["#".repeat(node.depth) + " ", printChildren(path$$1, options, print)]);
case "code":
{
if ( // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
/^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
// indented code block
var alignment = " ".repeat(4);
return align$2(alignment, concat$10([alignment, join$8(hardline$9, node.value.split("\n"))]));
} // fenced code block
var styleUnit = options.__inJsTemplate ? "~" : "`";
var _style2 = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
return concat$10([_style2, node.lang || "", hardline$9, join$8(hardline$9, node.value.split("\n")), hardline$9, _style2]);
}
case "front-matter":
return node.value;
case "html":
{
var _parentNode2 = path$$1.getParentNode();
var value = _parentNode2.type === "root" && util$1.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value;
var isHtmlComment = /^$/.test(value);
return replaceNewlinesWith(value, isHtmlComment ? hardline$9 : markAsRoot$1(literalline$3));
}
case "list":
{
var nthSiblingIndex = getNthListSiblingIndex(node, path$$1.getParentNode());
var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && /^\s*1(\.|\))/.test(options.originalText.slice(node.children[1].position.start.offset, node.children[1].position.end.offset));
return printChildren(path$$1, options, print, {
processor: function processor(childPath, index) {
var prefix = getPrefix();
return concat$10([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
function getPrefix() {
var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* "; // do not print trailing spaces for empty list item since it might be treated as `break` node
// by [doc-printer](https://github.com/prettier/prettier/blob/1.10.2/src/doc/doc-printer.js#L395-L405),
// we don't want to preserve unnecessary trailing spaces.
var listItem = childPath.getValue();
return listItem.children.length ? alignListPrefix(rawPrefix, options) : rawPrefix;
}
}
});
}
case "thematicBreak":
{
var counter = getAncestorCounter$1(path$$1, "list");
if (counter === -1) {
return "---";
}
var _nthSiblingIndex = getNthListSiblingIndex(path$$1.getParentNode(counter), path$$1.getParentNode(counter + 1));
return _nthSiblingIndex % 2 === 0 ? "***" : "---";
}
case "linkReference":
return concat$10(["[", printChildren(path$$1, options, print), "]", node.referenceType === "full" ? concat$10(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
case "imageReference":
switch (node.referenceType) {
case "full":
return concat$10(["![", node.alt || "", "][", node.identifier, "]"]);
default:
return concat$10(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
}
case "definition":
{
var lineOrSpace = options.proseWrap === "always" ? line$7 : " ";
return group$5(concat$10([concat$10(["[", node.identifier, "]:"]), indent$8(concat$10([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$10([lineOrSpace, printTitle(node.title, options, false)])]))]));
}
case "footnote":
return concat$10(["[^", printChildren(path$$1, options, print), "]"]);
case "footnoteReference":
return concat$10(["[^", node.identifier, "]"]);
case "footnoteDefinition":
{
var _nextNode2 = path$$1.getParentNode().children[path$$1.getName() + 1];
return concat$10(["[^", node.identifier, "]: ", group$5(concat$10([align$2(" ".repeat(options.tabWidth), printChildren(path$$1, options, print, {
processor: function processor(childPath, index) {
return index === 0 ? group$5(concat$10([softline$6, softline$6, childPath.call(print)])) : childPath.call(print);
}
})), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$6 : ""]))]);
}
case "table":
return printTable(path$$1, options, print);
case "tableCell":
return printChildren(path$$1, options, print);
case "break":
return /\s/.test(options.originalText[node.position.start.offset]) ? concat$10([" ", markAsRoot$1(literalline$3)]) : concat$10(["\\", hardline$9]);
case "liquidNode":
return replaceNewlinesWith(node.value, hardline$9);
case "tableRow": // handled in "table"
case "listItem": // handled in "list"
default:
throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
}
}
function printListItem(path$$1, options, print, listPrefix) {
var node = path$$1.getValue();
var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
return concat$10([prefix, printChildren(path$$1, options, print, {
processor: function processor(childPath, index) {
if (index === 0 && childPath.getValue().type !== "list") {
return align$2(" ".repeat(prefix.length), childPath.call(print));
}
var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
return concat$10([alignment, align$2(alignment, childPath.call(print))]);
}
})]);
}
function alignListPrefix(prefix, options) {
var additionalSpaces = getAdditionalSpaces();
return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
);
function getAdditionalSpaces() {
var restSpaces = prefix.length % options.tabWidth;
return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
}
}
function getNthListSiblingIndex(node, parentNode) {
return getNthSiblingIndex(node, parentNode, function (siblingNode) {
return siblingNode.ordered === node.ordered;
});
}
function replaceNewlinesWith(str, doc$$2) {
return join$8(doc$$2, str.split("\n"));
}
function getNthSiblingIndex(node, parentNode, condition) {
condition = condition || function () {
return true;
};
var index = -1;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var childNode = _step.value;
if (childNode.type === node.type && condition(childNode)) {
index++;
} else {
index = -1;
}
if (childNode === node) {
return index;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
function getAncestorCounter$1(path$$1, typeOrTypes) {
var types = [].concat(typeOrTypes);
var counter = -1;
var ancestorNode;
while (ancestorNode = path$$1.getParentNode(++counter)) {
if (types.indexOf(ancestorNode.type) !== -1) {
return counter;
}
}
return -1;
}
function getAncestorNode$2(path$$1, typeOrTypes) {
var counter = getAncestorCounter$1(path$$1, typeOrTypes);
return counter === -1 ? null : path$$1.getParentNode(counter);
}
function printLine(path$$1, value, options) {
if (options.proseWrap === "preserve" && value === "\n") {
return hardline$9;
}
var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path$$1, SINGLE_LINE_NODE_TYPES);
return value !== "" ? isBreakable ? line$7 : " " : isBreakable ? softline$6 : "";
}
function printTable(path$$1, options, print) {
var node = path$$1.getValue();
var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
path$$1.map(function (rowPath) {
var rowContents = [];
rowPath.map(function (cellPath) {
rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
}, "children");
contents.push(rowContents);
}, "children");
var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) {
return currentWidths.map(function (width, columnIndex) {
return Math.max(width, util$1.getStringWidth(rowContents[columnIndex]));
});
}, contents[0].map(function () {
return 3;
}) // minimum width = 3 (---, :--, :-:, --:)
);
return join$8(hardline$9, [printRow(contents[0]), printSeparator(), join$8(hardline$9, contents.slice(1).map(printRow))]);
function printSeparator() {
return concat$10(["| ", join$8(" | ", columnMaxWidths.map(function (width, index) {
switch (node.align[index]) {
case "left":
return ":" + "-".repeat(width - 1);
case "right":
return "-".repeat(width - 1) + ":";
case "center":
return ":" + "-".repeat(width - 2) + ":";
default:
return "-".repeat(width);
}
})), " |"]);
}
function printRow(rowContents) {
return concat$10(["| ", join$8(" | ", rowContents.map(function (rowContent, columnIndex) {
switch (node.align[columnIndex]) {
case "right":
return alignRight(rowContent, columnMaxWidths[columnIndex]);
case "center":
return alignCenter(rowContent, columnMaxWidths[columnIndex]);
default:
return alignLeft(rowContent, columnMaxWidths[columnIndex]);
}
})), " |"]);
}
function alignLeft(text, width) {
return concat$10([text, " ".repeat(width - util$1.getStringWidth(text))]);
}
function alignRight(text, width) {
return concat$10([" ".repeat(width - util$1.getStringWidth(text)), text]);
}
function alignCenter(text, width) {
var spaces = width - util$1.getStringWidth(text);
var left = Math.floor(spaces / 2);
var right = spaces - left;
return concat$10([" ".repeat(left), text, " ".repeat(right)]);
}
}
function printRoot(path$$1, options, print) {
/** @typedef {{ index: number, offset: number }} IgnorePosition */
/** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
var ignoreRanges = [];
/** @type {IgnorePosition | null} */
var ignoreStart = null;
var children = path$$1.getValue().children;
children.forEach(function (childNode, index) {
switch (isPrettierIgnore(childNode)) {
case "start":
if (ignoreStart === null) {
ignoreStart = {
index,
offset: childNode.position.end.offset
};
}
break;
case "end":
if (ignoreStart !== null) {
ignoreRanges.push({
start: ignoreStart,
end: {
index,
offset: childNode.position.start.offset
}
});
ignoreStart = null;
}
break;
default:
// do nothing
break;
}
});
return printChildren(path$$1, options, print, {
processor: function processor(childPath, index) {
if (ignoreRanges.length !== 0) {
var ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
return concat$10([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
}
if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
return false;
}
if (index === ignoreRange.end.index) {
ignoreRanges.shift();
return false;
}
}
return childPath.call(print);
}
});
}
function printChildren(path$$1, options, print, events$$1) {
events$$1 = events$$1 || {};
var postprocessor = events$$1.postprocessor || concat$10;
var processor = events$$1.processor || function (childPath) {
return childPath.call(print);
};
var node = path$$1.getValue();
var parts = [];
var lastChildNode;
path$$1.map(function (childPath, index) {
var childNode = childPath.getValue();
var result = processor(childPath, index);
if (result !== false) {
var data = {
parts,
prevNode: lastChildNode,
parentNode: node,
options
};
if (!shouldNotPrePrintHardline(childNode, data)) {
parts.push(hardline$9);
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$9);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$9);
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor(parts);
}
/** @return {false | 'next' | 'start' | 'end'} */
function isPrettierIgnore(node) {
if (node.type !== "html") {
return false;
}
var match = node.value.match(/^$/);
return match === null ? false : match[1] ? match[1] : "next";
}
function shouldNotPrePrintHardline(node, data) {
var isFirstNode = data.parts.length === 0;
var isInlineNode = INLINE_NODE_TYPES.indexOf(node.type) !== -1;
var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.indexOf(data.parentNode.type) !== -1;
return isFirstNode || isInlineNode || isInlineHTML;
}
function shouldPrePrintDoubleHardline(node, data) {
var isSequence = (data.prevNode && data.prevNode.type) === node.type;
var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(node.type) !== -1;
var isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
var isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
var isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
var isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml);
}
function shouldPrePrintTripleHardline(node, data) {
var isPrevNodeList = data.prevNode && data.prevNode.type === "list";
var isIndentedCode = node.type === "code" && /\s/.test(data.options.originalText[node.position.start.offset]);
return isPrevNodeList && isIndentedCode;
}
function shouldRemainTheSameContent(path$$1) {
var ancestorNode = getAncestorNode$2(path$$1, ["linkReference", "imageReference"]);
return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
}
function normalizeDoc(doc$$2) {
return mapDoc$3(doc$$2, function (currentDoc) {
if (!currentDoc.parts) {
return currentDoc;
}
if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
return currentDoc.parts[0];
}
var parts = [];
currentDoc.parts.forEach(function (part) {
if (part.type === "concat") {
parts.push.apply(parts, part.parts);
} else if (part !== "") {
parts.push(part);
}
});
return Object.assign({}, currentDoc, {
parts: normalizeParts(parts)
});
});
}
function printUrl(url, dangerousCharOrChars) {
var dangerousChars = [" "].concat(dangerousCharOrChars || []);
return new RegExp(dangerousChars.map(function (x) {
return `\\${x}`;
}).join("|")).test(url) ? `<${url}>` : url;
}
function printTitle(title, options, printSpace) {
if (printSpace == null) {
printSpace = true;
}
if (!title) {
return "";
}
if (printSpace) {
return " " + printTitle(title, options, false);
}
if (title.includes('"') && title.includes("'") && !title.includes(")")) {
return `(${title})`; // avoid escaped quotes
} // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
var singleCount = title.split("'").length - 1;
var doubleCount = title.split('"').length - 1;
var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
return `${quote}${title}${quote}`;
}
function normalizeParts(parts) {
return parts.reduce(function (current, part) {
var lastPart = util$1.getLast(current);
if (typeof lastPart === "string" && typeof part === "string") {
current.splice(-1, 1, lastPart + part);
} else {
current.push(part);
}
return current;
}, []);
}
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function clean$7(ast, newObj, parent) {
delete newObj.position; // for codeblock
if (ast.type === "code") {
delete newObj.value;
} // for whitespace: "\n" and " " are considered the same
if (ast.type === "whitespace" && ast.value === "\n") {
newObj.value = " ";
} // for insert pragma
if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || parent.children[0].type === "front-matter" && parent.children[1] === ast) && ast.type === "html" && pragma$2.startWithPragma(ast.value)) {
return null;
}
}
function hasPrettierIgnore$1(path$$1) {
var index = +path$$1.getName();
if (index === 0) {
return false;
}
var prevNode = path$$1.getParentNode().children[index - 1];
return isPrettierIgnore(prevNode) === "next";
}
var printerMarkdown = {
print: genericPrint$5,
embed: embed_1$2,
massageAstNode: clean$7,
hasPrettierIgnore: hasPrettierIgnore$1,
insertPragma: pragma$2.insertPragma
};
var CATEGORY_MARKDOWN = "Markdown"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var options$13 = {
proseWrap: {
since: "1.8.2",
category: CATEGORY_MARKDOWN,
type: "choice",
default: [{
since: "1.8.2",
value: true
}, {
since: "1.9.0",
value: "preserve"
}],
description: "How to wrap prose. (markdown)",
choices: [{
since: "1.9.0",
value: "always",
description: "Wrap prose if it exceeds the print width."
}, {
since: "1.9.0",
value: "never",
description: "Do not wrap prose."
}, {
since: "1.9.0",
value: "preserve",
description: "Wrap prose as-is."
}, {
value: false,
deprecated: "1.9.0",
redirect: "never"
}, {
value: true,
deprecated: "1.9.0",
redirect: "always"
}]
},
singleQuote: commonOptions.singleQuote
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$4 = [{
name: "Markdown",
since: "1.8.0",
parsers: ["remark"],
aliases: ["pandoc"],
aceMode: "markdown",
codemirrorMode: "gfm",
codemirrorMimeType: "text/x-gfm",
wrap: true,
extensions: [".md", ".markdown", ".mdown", ".mdwn", ".mkd", ".mkdn", ".mkdown", ".ron", ".workbook"],
filenames: ["README"],
tmScope: "source.gfm",
linguistLanguageId: 222,
vscodeLanguageIds: ["markdown"]
}];
var printers$4 = {
mdast: printerMarkdown
};
var languageMarkdown = {
languages: languages$4,
options: options$13,
printers: printers$4
};
var hasNewlineInRange$3 = util$1.hasNewlineInRange;
var _require$$1$builders$1 = doc.builders;
var hardline$12 = _require$$1$builders$1.hardline;
var concat$13 = _require$$1$builders$1.concat;
var _require$$1$utils = doc.utils;
var stripTrailingHardline$2 = _require$$1$utils.stripTrailingHardline;
var removeLines$3 = _require$$1$utils.removeLines;
function embed$4(path$$1, print, textToDoc, options) {
var node = path$$1.getValue();
switch (node.type) {
case "text":
{
var parent = path$$1.getParentNode(); // Inline JavaScript
if (parent.type === "script" && (!parent.attribs.lang && !parent.attribs.lang || parent.attribs.type === "text/javascript" || parent.attribs.type === "application/javascript")) {
var parser = options.parser === "flow" ? "flow" : "babylon";
var doc$$2 = textToDoc(getText(options, node), {
parser
});
return concat$13([hardline$12, doc$$2]);
} // Inline TypeScript
if (parent.type === "script" && (parent.attribs.type === "application/x-typescript" || parent.attribs.lang === "ts")) {
var _doc = textToDoc(getText(options, node), {
parser: "typescript"
}, options);
return concat$13([hardline$12, _doc]);
} // Inline Styles
if (parent.type === "style") {
var _doc2 = textToDoc(getText(options, node), {
parser: "css"
});
return concat$13([hardline$12, stripTrailingHardline$2(_doc2)]);
}
break;
}
case "attribute":
{
/*
* Vue binding sytax: JS expressions
* :class="{ 'some-key': value }"
* v-bind:id="'list-' + id"
* v-if="foo && !bar"
* @click="someFunction()"
*/
if (/(^@)|(^v-)|:/.test(node.key) && !/^\w+$/.test(node.value)) {
var _doc3 = textToDoc(node.value, {
parser: parseJavaScriptExpression,
// Use singleQuote since HTML attributes use double-quotes.
// TODO(azz): We still need to do an entity escape on the attribute.
singleQuote: true
});
return concat$13([node.key, '="', hasNewlineInRange$3(node.value, 0, node.value.length) ? _doc3 : removeLines$3(_doc3), '"']);
}
}
}
}
function parseJavaScriptExpression(text, parsers) {
// Force parsing as an expression
var ast = parsers.babylon(`(${text})`); // Extract expression from the declaration
return {
type: "File",
program: ast.program.body[0].expression
};
}
function getText(options, node) {
return options.originalText.slice(options.locStart(node), options.locEnd(node));
}
var embed_1$4 = embed$4;
var clean$8 = function clean(ast, newNode) {
delete newNode.__location;
if (ast.type === "text") {
return null;
}
};
var hasNewlineInRange$2 = util$1.hasNewlineInRange;
var hasIgnoreComment$4 = util$1.hasIgnoreComment;
var _require$$1$builders = doc.builders;
var concat$12 = _require$$1$builders.concat;
var join$9 = _require$$1$builders.join;
var hardline$11 = _require$$1$builders.hardline;
var line$8 = _require$$1$builders.line;
var softline$7 = _require$$1$builders.softline;
var group$6 = _require$$1$builders.group;
var indent$9 = _require$$1$builders.indent; // http://w3c.github.io/html/single-page.html#void-elements
var voidTags$1 = {
area: true,
base: true,
br: true,
col: true,
embed: true,
hr: true,
img: true,
input: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true
};
function genericPrint$6(path$$1, options, print) {
var n = path$$1.getValue();
if (!n) {
return "";
}
if (typeof n === "string") {
return n;
}
switch (n.type) {
case "root":
{
return printChildren$1(path$$1, print);
}
case "directive":
{
return concat$12(["<", n.data, ">", hardline$11]);
}
case "text":
{
return n.data.replace(/\s+/g, " ").trim();
}
case "script":
case "style":
case "tag":
{
var selfClose = voidTags$1[n.name] ? ">" : " />";
var children = printChildren$1(path$$1, print);
var hasNewline = hasNewlineInRange$2(options.originalText, options.locStart(n), options.locEnd(n));
return group$6(concat$12([hasNewline ? hardline$11 : "", "<", n.name, printAttributes(path$$1, print), n.children.length ? ">" : selfClose, n.name.toLowerCase() === "html" ? concat$12([hardline$11, children]) : indent$9(children), n.children.length ? concat$12([softline$7, "", n.name, ">"]) : hardline$11]));
}
case "comment":
{
return concat$12([""]);
}
case "attribute":
{
if (!n.value) {
return n.key;
}
return concat$12([n.key, '="', n.value, '"']);
}
default:
/* istanbul ignore next */
throw new Error("unknown htmlparser2 type: " + n.type);
}
}
function printAttributes(path$$1, print) {
var node = path$$1.getValue();
return concat$12([node.attributes.length ? " " : "", indent$9(join$9(line$8, path$$1.map(print, "attributes")))]);
}
function printChildren$1(path$$1, print) {
var children = [];
path$$1.each(function (childPath) {
var child = childPath.getValue();
if (child.type !== "text") {
children.push(hardline$11);
}
children.push(childPath.call(print));
}, "children");
return concat$12(children);
}
var printerHtmlparser2 = {
print: genericPrint$6,
massageAstNode: clean$8,
embed: embed_1$4,
hasPrettierIgnore: hasIgnoreComment$4
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$5 = [{
name: "HTML",
since: null,
// unreleased
parsers: ["parse5"],
group: "HTML",
tmScope: "text.html.basic",
aceMode: "html",
codemirrorMode: "htmlmixed",
codemirrorMimeType: "text/html",
aliases: ["xhtml"],
extensions: [".html", ".htm", ".html.hl", ".inc", ".st", ".xht", ".xhtml"],
linguistLanguageId: 146,
vscodeLanguageIds: ["html"]
}];
var printers$5 = {
htmlparser2: printerHtmlparser2
};
var languageHtml = {
languages: languages$5,
printers: printers$5
};
var _require$$0$builders$8 = doc.builders;
var concat$15 = _require$$0$builders$8.concat;
var hardline$14 = _require$$0$builders$8.hardline;
function embed$6(path$$1, print, textToDoc, options) {
var node = path$$1.getValue();
var parent = path$$1.getParentNode();
if (!parent || parent.tag !== "root" || node.unary) {
return null;
}
var parser;
if (node.tag === "style") {
var langAttr = node.attrs.find(function (attr) {
return attr.name === "lang";
});
if (!langAttr || langAttr.value === "postcss") {
parser = "css";
} else if (langAttr.value === "scss") {
parser = "scss";
} else if (langAttr.value === "less") {
parser = "less";
}
}
if (node.tag === "script") {
var _langAttr = node.attrs.find(function (attr) {
return attr.name === "lang";
});
if (!_langAttr) {
parser = "babylon";
} else if (_langAttr.value === "ts" || _langAttr.value === "tsx") {
parser = "typescript";
}
}
if (!parser) {
return null;
}
return concat$15([options.originalText.slice(node.start, node.contentStart), hardline$14, textToDoc(options.originalText.slice(node.contentStart, node.contentEnd), {
parser
}), options.originalText.slice(node.contentEnd, node.end)]);
}
var embed_1$6 = embed$6;
var _require$$0$builders$7 = doc.builders;
var concat$14 = _require$$0$builders$7.concat;
var hardline$13 = _require$$0$builders$7.hardline;
function genericPrint$7(path$$1, options, print) {
var n = path$$1.getValue();
var res = [];
var index = n.start;
path$$1.each(function (childPath) {
var child = childPath.getValue();
res.push(options.originalText.slice(index, child.start));
res.push(childPath.call(print));
index = child.end;
}, "children"); // If there are no children, we just print the node from start to end.
// Otherwise, index should point to the end of the last child, and we
// need to print the closing tag.
res.push(options.originalText.slice(index, n.end)); // Only force a trailing newline if there were any contents.
if (n.tag === "root" && n.children.length) {
res.push(hardline$13);
}
return concat$14(res);
}
var clean$11 = function clean(ast, newObj) {
delete newObj.start;
delete newObj.end;
delete newObj.contentStart;
delete newObj.contentEnd;
};
var printerVue = {
print: genericPrint$7,
embed: embed_1$6,
massageAstNode: clean$11
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$6 = [{
name: "Vue",
since: "1.10.0",
parsers: ["vue"],
group: "HTML",
tmScope: "text.html.vue",
aceMode: "html",
codemirrorMode: "htmlmixed",
codemirrorMimeType: "text/html",
extensions: [".vue"],
linguistLanguageId: 146,
vscodeLanguageIds: ["vue"]
}];
var printers$6 = {
vue: printerVue
};
var languageVue = {
languages: languages$6,
printers: printers$6
};
// plugin will look for `eval("require")()` and transform to `require()` in the bundle,
// and rewrite the paths to require from the top-level.
// We need to list the parsers and getters so we can load them only when necessary.
var internalPlugins = [// JS
languageJs, {
parsers: {
// JS - Babylon
get babylon() {
return require("./parser-babylon").parsers.babylon;
},
get json() {
return require("./parser-babylon").parsers.json;
},
get json5() {
return require("./parser-babylon").parsers.json5;
},
get "json-stringify"() {
return require("./parser-babylon").parsers["json-stringify"];
},
// JS - Flow
get flow() {
return require("./parser-flow").parsers.flow;
},
// JS - TypeScript
get typescript() {
return require("./parser-typescript").parsers.typescript;
},
get "typescript-eslint"() {
return require("./parser-typescript").parsers["typescript-eslint"];
}
}
}, // CSS
languageCss, {
parsers: {
// TODO: switch these to just `postcss` and use `language` instead.
get css() {
return require("./parser-postcss").parsers.css;
},
get less() {
return require("./parser-postcss").parsers.css;
},
get scss() {
return require("./parser-postcss").parsers.css;
}
}
}, // Handlebars
languageHandlebars, {
parsers: {
get glimmer() {
return require("./parser-glimmer").parsers.glimmer;
}
}
}, // GraphQL
languageGraphql, {
parsers: {
get graphql() {
return require("./parser-graphql").parsers.graphql;
}
}
}, // Markdown
languageMarkdown, {
parsers: {
get remark() {
return require("./parser-markdown").parsers.remark;
},
// TODO: Delete this in 2.0
get markdown() {
return require("./parser-markdown").parsers.remark;
}
}
}, // HTML
languageHtml, {
parsers: {
get parse5() {
return require("./parser-parse5").parsers.parse5;
}
}
}, // Vue
languageVue, {
parsers: {
get vue() {
return require("./parser-vue").parsers.vue;
}
}
}];
var thirdParty$1 = ( thirdParty && thirdParty__default ) || thirdParty;
function loadPlugins(plugins, pluginSearchDirs) {
if (!plugins) {
plugins = [];
}
if (!pluginSearchDirs) {
pluginSearchDirs = [];
} // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
if (!pluginSearchDirs.length) {
var autoLoadDir = thirdParty$1.findParentDir(thirdParty$1.findParentDir(__dirname, "prettier"), "node_modules");
if (autoLoadDir) {
pluginSearchDirs = [autoLoadDir];
}
}
var externalManualLoadPluginInfos = plugins.map(function (pluginName) {
var requirePath;
try {
// try local files
requirePath = resolve$1.sync(path.resolve(process.cwd(), pluginName));
} catch (e) {
// try node modules
requirePath = resolve$1.sync(pluginName, {
basedir: process.cwd()
});
}
return {
name: pluginName,
requirePath
};
});
var externalAutoLoadPluginInfos = pluginSearchDirs.map(function (pluginSearchDir) {
var resolvedPluginSearchDir = path.resolve(process.cwd(), pluginSearchDir);
if (!isDirectory(resolvedPluginSearchDir)) {
throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
}
var nodeModulesDir = path.resolve(resolvedPluginSearchDir, "node_modules");
return findPluginsInNodeModules(nodeModulesDir).map(function (pluginName) {
return {
name: pluginName,
requirePath: resolve$1.sync(pluginName, {
basedir: resolvedPluginSearchDir
})
};
});
}).reduce(function (a, b) {
return a.concat(b);
}, []);
var externalPlugins = lodash_uniqby(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(function (externalPluginInfo) {
return Object.assign({
name: externalPluginInfo.name
}, require(externalPluginInfo.requirePath));
});
return internalPlugins.concat(externalPlugins);
}
function findPluginsInNodeModules(nodeModulesDir) {
var pluginPackageJsonPaths = globby.sync(["prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
cwd: nodeModulesDir
});
return pluginPackageJsonPaths.map(path.dirname);
}
function isDirectory(dir) {
try {
return fs.statSync(dir).isDirectory();
} catch (e) {
return false;
}
}
var loadPlugins_1 = loadPlugins;
var mimicFn = function mimicFn(to, from) {
// TODO: use `Reflect.ownKeys()` when targeting Node.js 6
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var prop = _step.value;
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
var mem = createCommonjsModule(function (module) {
'use strict';
var cacheStore = new WeakMap();
var defaultCacheKey = function defaultCacheKey(x) {
if (arguments.length === 1 && (x === null || x === undefined || typeof x !== 'function' && typeof x !== 'object')) {
return x;
}
return JSON.stringify(arguments);
};
module.exports = function (fn, opts) {
opts = Object.assign({
cacheKey: defaultCacheKey,
cache: new Map()
}, opts);
var memoized = function memoized() {
var cache = cacheStore.get(memoized);
var key = opts.cacheKey.apply(null, arguments);
if (cache.has(key)) {
var c = cache.get(key);
if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) {
return c.data;
}
}
var ret = fn.apply(null, arguments);
cache.set(key, {
data: ret,
maxAge: Date.now() + (opts.maxAge || 0)
});
return ret;
};
mimicFn(memoized, fn);
cacheStore.set(memoized, opts.cache);
return memoized;
};
module.exports.clear = function (fn) {
var cache = cacheStore.get(fn);
if (cache && typeof cache.clear === 'function') {
cache.clear();
}
};
});
var semver$3 = createCommonjsModule(function (module, exports) {
exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version.
/* nomin */
var debug;
/* nomin */
if (typeof process === 'object' &&
/* nomin */
process.env &&
/* nomin */
process.env.NODE_DEBUG &&
/* nomin */
/\bsemver\b/i.test(process.env.NODE_DEBUG))
/* nomin */
debug = function debug() {
/* nomin */
var args = Array.prototype.slice.call(arguments, 0);
/* nomin */
args.unshift('SEMVER');
/* nomin */
console.log.apply(console, args);
/* nomin */
};
/* nomin */
else
/* nomin */
debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
exports.SEMVER_SPEC_VERSION = '2.0.0';
var MAX_LENGTH = 256;
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Max safe segment length for coercion.
var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
var re = exports.re = [];
var src = exports.src = [];
var R = 0; // The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
var NUMERICIDENTIFIER = R++;
src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
var NUMERICIDENTIFIERLOOSE = R++;
src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
var NONNUMERICIDENTIFIER = R++;
src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
// Three dot-separated numeric identifiers.
var MAINVERSION = R++;
src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
var MAINVERSIONLOOSE = R++;
src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
var PRERELEASEIDENTIFIER = R++;
src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
var PRERELEASEIDENTIFIERLOOSE = R++;
src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
var PRERELEASE = R++;
src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
var PRERELEASELOOSE = R++;
src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
var BUILDIDENTIFIER = R++;
src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
var BUILD = R++;
src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
var FULL = R++;
var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
var LOOSE = R++;
src[LOOSE] = '^' + LOOSEPLAIN + '$';
var GTLT = R++;
src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
var XRANGEIDENTIFIERLOOSE = R++;
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
var XRANGEIDENTIFIER = R++;
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
var XRANGEPLAIN = R++;
src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
var XRANGEPLAINLOOSE = R++;
src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
var XRANGE = R++;
src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
var XRANGELOOSE = R++;
src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
// Extract anything that could conceivably be a part of a valid semver
var COERCE = R++;
src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
// Meaning is "reasonably at or greater than"
var LONETILDE = R++;
src[LONETILDE] = '(?:~>?)';
var TILDETRIM = R++;
src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
var tildeTrimReplace = '$1~';
var TILDE = R++;
src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
var TILDELOOSE = R++;
src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
// Meaning is "at least and backwards compatible with"
var LONECARET = R++;
src[LONECARET] = '(?:\\^)';
var CARETTRIM = R++;
src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
var caretTrimReplace = '$1^';
var CARET = R++;
src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
var CARETLOOSE = R++;
src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
var COMPARATORLOOSE = R++;
src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
var COMPARATOR = R++;
src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
var COMPARATORTRIM = R++;
src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
var HYPHENRANGE = R++;
src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
var HYPHENRANGELOOSE = R++;
src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
var STAR = R++;
src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
for (var i = 0; i < R; i++) {
debug(i, src[i]);
if (!re[i]) re[i] = new RegExp(src[i]);
}
exports.parse = parse;
function parse(version, loose) {
if (version instanceof SemVer) return version;
if (typeof version !== 'string') return null;
if (version.length > MAX_LENGTH) return null;
var r = loose ? re[LOOSE] : re[FULL];
if (!r.test(version)) return null;
try {
return new SemVer(version, loose);
} catch (er) {
return null;
}
}
exports.valid = valid;
function valid(version, loose) {
var v = parse(version, loose);
return v ? v.version : null;
}
exports.clean = clean;
function clean(version, loose) {
var s = parse(version.trim().replace(/^[=v]+/, ''), loose);
return s ? s.version : null;
}
exports.SemVer = SemVer;
function SemVer(version, loose) {
if (version instanceof SemVer) {
if (version.loose === loose) return version;else version = version.version;
} else if (typeof version !== 'string') {
throw new TypeError('Invalid Version: ' + version);
}
if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
if (!(this instanceof SemVer)) return new SemVer(version, loose);
debug('SemVer', version, loose);
this.loose = loose;
var m = version.trim().match(loose ? re[LOOSE] : re[FULL]);
if (!m) throw new TypeError('Invalid Version: ' + version);
this.raw = version; // these are actually numbers
this.major = +m[1];
this.minor = +m[2];
this.patch = +m[3];
if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version');
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version');
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids
if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) {
if (/^[0-9]+$/.test(id)) {
var num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER) return num;
}
return id;
});
this.build = m[5] ? m[5].split('.') : [];
this.format();
}
SemVer.prototype.format = function () {
this.version = this.major + '.' + this.minor + '.' + this.patch;
if (this.prerelease.length) this.version += '-' + this.prerelease.join('.');
return this.version;
};
SemVer.prototype.toString = function () {
return this.version;
};
SemVer.prototype.compare = function (other) {
debug('SemVer.compare', this.version, this.loose, other);
if (!(other instanceof SemVer)) other = new SemVer(other, this.loose);
return this.compareMain(other) || this.comparePre(other);
};
SemVer.prototype.compareMain = function (other) {
if (!(other instanceof SemVer)) other = new SemVer(other, this.loose);
return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
};
SemVer.prototype.comparePre = function (other) {
if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); // NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) return -1;else if (!this.prerelease.length && other.prerelease.length) return 1;else if (!this.prerelease.length && !other.prerelease.length) return 0;
var i = 0;
do {
var a = this.prerelease[i];
var b = other.prerelease[i];
debug('prerelease compare', i, a, b);
if (a === undefined && b === undefined) return 0;else if (b === undefined) return 1;else if (a === undefined) return -1;else if (a === b) continue;else return compareIdentifiers(a, b);
} while (++i);
}; // preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
SemVer.prototype.inc = function (release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc('pre', identifier);
break;
case 'preminor':
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc('pre', identifier);
break;
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0;
this.inc('patch', identifier);
this.inc('pre', identifier);
break;
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) this.inc('patch', identifier);
this.inc('pre', identifier);
break;
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++;
this.minor = 0;
this.patch = 0;
this.prerelease = [];
break;
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) this.minor++;
this.patch = 0;
this.prerelease = [];
break;
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) this.patch++;
this.prerelease = [];
break;
// This probably shouldn't be used publicly.
// 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) this.prerelease = [0];else {
var i = this.prerelease.length;
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++;
i = -2;
}
}
if (i === -1) // didn't increment anything
this.prerelease.push(0);
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (this.prerelease[0] === identifier) {
if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0];
} else this.prerelease = [identifier, 0];
}
break;
default:
throw new Error('invalid increment argument: ' + release);
}
this.format();
this.raw = this.version;
return this;
};
exports.inc = inc;
function inc(version, release, loose, identifier) {
if (typeof loose === 'string') {
identifier = loose;
loose = undefined;
}
try {
return new SemVer(version, loose).inc(release, identifier).version;
} catch (er) {
return null;
}
}
exports.diff = diff;
function diff(version1, version2) {
if (eq(version1, version2)) {
return null;
} else {
var v1 = parse(version1);
var v2 = parse(version2);
if (v1.prerelease.length || v2.prerelease.length) {
for (var key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return 'pre' + key;
}
}
}
return 'prerelease';
}
for (var key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return key;
}
}
}
}
}
exports.compareIdentifiers = compareIdentifiers;
var numeric = /^[0-9]+$/;
function compareIdentifiers(a, b) {
var anum = numeric.test(a);
var bnum = numeric.test(b);
if (anum && bnum) {
a = +a;
b = +b;
}
return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0;
}
exports.rcompareIdentifiers = rcompareIdentifiers;
function rcompareIdentifiers(a, b) {
return compareIdentifiers(b, a);
}
exports.major = major;
function major(a, loose) {
return new SemVer(a, loose).major;
}
exports.minor = minor;
function minor(a, loose) {
return new SemVer(a, loose).minor;
}
exports.patch = patch;
function patch(a, loose) {
return new SemVer(a, loose).patch;
}
exports.compare = compare;
function compare(a, b, loose) {
return new SemVer(a, loose).compare(new SemVer(b, loose));
}
exports.compareLoose = compareLoose;
function compareLoose(a, b) {
return compare(a, b, true);
}
exports.rcompare = rcompare;
function rcompare(a, b, loose) {
return compare(b, a, loose);
}
exports.sort = sort;
function sort(list, loose) {
return list.sort(function (a, b) {
return exports.compare(a, b, loose);
});
}
exports.rsort = rsort;
function rsort(list, loose) {
return list.sort(function (a, b) {
return exports.rcompare(a, b, loose);
});
}
exports.gt = gt;
function gt(a, b, loose) {
return compare(a, b, loose) > 0;
}
exports.lt = lt;
function lt(a, b, loose) {
return compare(a, b, loose) < 0;
}
exports.eq = eq;
function eq(a, b, loose) {
return compare(a, b, loose) === 0;
}
exports.neq = neq;
function neq(a, b, loose) {
return compare(a, b, loose) !== 0;
}
exports.gte = gte;
function gte(a, b, loose) {
return compare(a, b, loose) >= 0;
}
exports.lte = lte;
function lte(a, b, loose) {
return compare(a, b, loose) <= 0;
}
exports.cmp = cmp;
function cmp(a, op, b, loose) {
var ret;
switch (op) {
case '===':
if (typeof a === 'object') a = a.version;
if (typeof b === 'object') b = b.version;
ret = a === b;
break;
case '!==':
if (typeof a === 'object') a = a.version;
if (typeof b === 'object') b = b.version;
ret = a !== b;
break;
case '':
case '=':
case '==':
ret = eq(a, b, loose);
break;
case '!=':
ret = neq(a, b, loose);
break;
case '>':
ret = gt(a, b, loose);
break;
case '>=':
ret = gte(a, b, loose);
break;
case '<':
ret = lt(a, b, loose);
break;
case '<=':
ret = lte(a, b, loose);
break;
default:
throw new TypeError('Invalid operator: ' + op);
}
return ret;
}
exports.Comparator = Comparator;
function Comparator(comp, loose) {
if (comp instanceof Comparator) {
if (comp.loose === loose) return comp;else comp = comp.value;
}
if (!(this instanceof Comparator)) return new Comparator(comp, loose);
debug('comparator', comp, loose);
this.loose = loose;
this.parse(comp);
if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version;
debug('comp', this);
}
var ANY = {};
Comparator.prototype.parse = function (comp) {
var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
var m = comp.match(r);
if (!m) throw new TypeError('Invalid comparator: ' + comp);
this.operator = m[1];
if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything.
if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.loose);
};
Comparator.prototype.toString = function () {
return this.value;
};
Comparator.prototype.test = function (version) {
debug('Comparator.test', version, this.loose);
if (this.semver === ANY) return true;
if (typeof version === 'string') version = new SemVer(version, this.loose);
return cmp(version, this.operator, this.semver, this.loose);
};
Comparator.prototype.intersects = function (comp, loose) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required');
}
var rangeTmp;
if (this.operator === '') {
rangeTmp = new Range(comp.value, loose);
return satisfies(this.value, rangeTmp, loose);
} else if (comp.operator === '') {
rangeTmp = new Range(this.value, loose);
return satisfies(comp.semver, rangeTmp, loose);
}
var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
var sameSemVer = this.semver.version === comp.semver.version;
var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, loose) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, loose) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
};
exports.Range = Range;
function Range(range, loose) {
if (range instanceof Range) {
if (range.loose === loose) {
return range;
} else {
return new Range(range.raw, loose);
}
}
if (range instanceof Comparator) {
return new Range(range.value, loose);
}
if (!(this instanceof Range)) return new Range(range, loose);
this.loose = loose; // First, split based on boolean or ||
this.raw = range;
this.set = range.split(/\s*\|\|\s*/).map(function (range) {
return this.parseRange(range.trim());
}, this).filter(function (c) {
// throw out any that are not relevant for whatever reason
return c.length;
});
if (!this.set.length) {
throw new TypeError('Invalid SemVer Range: ' + range);
}
this.format();
}
Range.prototype.format = function () {
this.range = this.set.map(function (comps) {
return comps.join(' ').trim();
}).join('||').trim();
return this.range;
};
Range.prototype.toString = function () {
return this.range;
};
Range.prototype.parseRange = function (range) {
var loose = this.loose;
range = range.trim();
debug('range', range, loose); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
range = range.replace(hr, hyphenReplace);
debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
// ready to be split into comparators.
var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
var set = range.split(' ').map(function (comp) {
return parseComparator(comp, loose);
}).join(' ').split(/\s+/);
if (this.loose) {
// in loose mode, throw out any that are not valid comparators
set = set.filter(function (comp) {
return !!comp.match(compRe);
});
}
set = set.map(function (comp) {
return new Comparator(comp, loose);
});
return set;
};
Range.prototype.intersects = function (range, loose) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required');
}
return this.set.some(function (thisComparators) {
return thisComparators.every(function (thisComparator) {
return range.set.some(function (rangeComparators) {
return rangeComparators.every(function (rangeComparator) {
return thisComparator.intersects(rangeComparator, loose);
});
});
});
});
}; // Mostly just for testing and legacy API reasons
exports.toComparators = toComparators;
function toComparators(range, loose) {
return new Range(range, loose).set.map(function (comp) {
return comp.map(function (c) {
return c.value;
}).join(' ').trim().split(' ');
});
} // comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
function parseComparator(comp, loose) {
debug('comp', comp);
comp = replaceCarets(comp, loose);
debug('caret', comp);
comp = replaceTildes(comp, loose);
debug('tildes', comp);
comp = replaceXRanges(comp, loose);
debug('xrange', comp);
comp = replaceStars(comp, loose);
debug('stars', comp);
return comp;
}
function isX(id) {
return !id || id.toLowerCase() === 'x' || id === '*';
} // ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
function replaceTildes(comp, loose) {
return comp.trim().split(/\s+/).map(function (comp) {
return replaceTilde(comp, loose);
}).join(' ');
}
function replaceTilde(comp, loose) {
var r = loose ? re[TILDELOOSE] : re[TILDE];
return comp.replace(r, function (_, M, m, p, pr) {
debug('tilde', comp, _, M, m, p, pr);
var ret;
if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) {
debug('replaceTilde pr', pr);
if (pr.charAt(0) !== '-') pr = '-' + pr;
ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
} else // ~1.2.3 == >=1.2.3 <1.3.0
ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
debug('tilde return', ret);
return ret;
});
} // ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
// ^1.2.3 --> >=1.2.3 <2.0.0
// ^1.2.0 --> >=1.2.0 <2.0.0
function replaceCarets(comp, loose) {
return comp.trim().split(/\s+/).map(function (comp) {
return replaceCaret(comp, loose);
}).join(' ');
}
function replaceCaret(comp, loose) {
debug('caret', comp, loose);
var r = loose ? re[CARETLOOSE] : re[CARET];
return comp.replace(r, function (_, M, m, p, pr) {
debug('caret', comp, _, M, m, p, pr);
var ret;
if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) {
if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
} else if (pr) {
debug('replaceCaret pr', pr);
if (pr.charAt(0) !== '-') pr = '-' + pr;
if (M === '0') {
if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
} else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0';
} else {
debug('no pr');
if (M === '0') {
if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
} else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
}
debug('caret return', ret);
return ret;
});
}
function replaceXRanges(comp, loose) {
debug('replaceXRanges', comp, loose);
return comp.split(/\s+/).map(function (comp) {
return replaceXRange(comp, loose);
}).join(' ');
}
function replaceXRange(comp, loose) {
comp = comp.trim();
var r = loose ? re[XRANGELOOSE] : re[XRANGE];
return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
debug('xRange', comp, ret, gtlt, M, m, p, pr);
var xM = isX(M);
var xm = xM || isX(m);
var xp = xm || isX(p);
var anyX = xp;
if (gtlt === '=' && anyX) gtlt = '';
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0';
} else {
// nothing is forbidden
ret = '*';
}
} else if (gtlt && anyX) {
// replace X with 0
if (xm) m = 0;
if (xp) p = 0;
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
// >1.2.3 => >= 1.2.4
gtlt = '>=';
if (xm) {
M = +M + 1;
m = 0;
p = 0;
} else if (xp) {
m = +m + 1;
p = 0;
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<';
if (xm) M = +M + 1;else m = +m + 1;
}
ret = gtlt + M + '.' + m + '.' + p;
} else if (xm) {
ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
} else if (xp) {
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
}
debug('xRange return', ret);
return ret;
});
} // Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
function replaceStars(comp, loose) {
debug('replaceStars', comp, loose); // Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[STAR], '');
} // This function is passed to string.replace(re[HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0
function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from;
if (isX(tM)) to = '';else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0';else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0';else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;else to = '<=' + to;
return (from + ' ' + to).trim();
} // if ANY of the sets match ALL of its comparators, then pass
Range.prototype.test = function (version) {
if (!version) return false;
if (typeof version === 'string') version = new SemVer(version, this.loose);
for (var i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version)) return true;
}
return false;
};
function testSet(set, version) {
for (var i = 0; i < set.length; i++) {
if (!set[i].test(version)) return false;
}
if (version.prerelease.length) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (var i = 0; i < set.length; i++) {
debug(set[i].semver);
if (set[i].semver === ANY) continue;
if (set[i].semver.prerelease.length > 0) {
var allowed = set[i].semver;
if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true;
}
} // Version has a -pre, but it's not one of the ones we like.
return false;
}
return true;
}
exports.satisfies = satisfies;
function satisfies(version, range, loose) {
try {
range = new Range(range, loose);
} catch (er) {
return false;
}
return range.test(version);
}
exports.maxSatisfying = maxSatisfying;
function maxSatisfying(versions, range, loose) {
var max = null;
var maxSV = null;
try {
var rangeObj = new Range(range, loose);
} catch (er) {
return null;
}
versions.forEach(function (v) {
if (rangeObj.test(v)) {
// satisfies(v, range, loose)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v;
maxSV = new SemVer(max, loose);
}
}
});
return max;
}
exports.minSatisfying = minSatisfying;
function minSatisfying(versions, range, loose) {
var min = null;
var minSV = null;
try {
var rangeObj = new Range(range, loose);
} catch (er) {
return null;
}
versions.forEach(function (v) {
if (rangeObj.test(v)) {
// satisfies(v, range, loose)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v;
minSV = new SemVer(min, loose);
}
}
});
return min;
}
exports.validRange = validRange;
function validRange(range, loose) {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, loose).range || '*';
} catch (er) {
return null;
}
} // Determine if version is less than all the versions possible in the range
exports.ltr = ltr;
function ltr(version, range, loose) {
return outside(version, range, '<', loose);
} // Determine if version is greater than all the versions possible in the range.
exports.gtr = gtr;
function gtr(version, range, loose) {
return outside(version, range, '>', loose);
}
exports.outside = outside;
function outside(version, range, hilo, loose) {
version = new SemVer(version, loose);
range = new Range(range, loose);
var gtfn, ltefn, ltfn, comp, ecomp;
switch (hilo) {
case '>':
gtfn = gt;
ltefn = lte;
ltfn = lt;
comp = '>';
ecomp = '>=';
break;
case '<':
gtfn = lt;
ltefn = gte;
ltfn = gt;
comp = '<';
ecomp = '<=';
break;
default:
throw new TypeError('Must provide a hilo val of "<" or ">"');
} // If it satisifes the range it is not outside
if (satisfies(version, range, loose)) {
return false;
} // From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (var i = 0; i < range.set.length; ++i) {
var comparators = range.set[i];
var high = null;
var low = null;
comparators.forEach(function (comparator) {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0');
}
high = high || comparator;
low = low || comparator;
if (gtfn(comparator.semver, high.semver, loose)) {
high = comparator;
} else if (ltfn(comparator.semver, low.semver, loose)) {
low = comparator;
}
}); // If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false;
} // If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
return false;
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false;
}
}
return true;
}
exports.prerelease = prerelease;
function prerelease(version, loose) {
var parsed = parse(version, loose);
return parsed && parsed.prerelease.length ? parsed.prerelease : null;
}
exports.intersects = intersects;
function intersects(r1, r2, loose) {
r1 = new Range(r1, loose);
r2 = new Range(r2, loose);
return r1.intersects(r2);
}
exports.coerce = coerce;
function coerce(version) {
if (version instanceof SemVer) return version;
if (typeof version !== 'string') return null;
var match = version.match(re[COERCE]);
if (match == null) return null;
return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
}
});
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var pseudomap = PseudoMap;
function PseudoMap(set) {
if (!(this instanceof PseudoMap)) // whyyyyyyy
throw new TypeError("Constructor PseudoMap requires 'new'");
this.clear();
if (set) {
if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
this.set(key, value);
}, this);else if (Array.isArray(set)) set.forEach(function (kv) {
this.set(kv[0], kv[1]);
}, this);else throw new TypeError('invalid argument');
}
}
PseudoMap.prototype.forEach = function (fn, thisp) {
thisp = thisp || this;
Object.keys(this._data).forEach(function (k) {
if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
}, this);
};
PseudoMap.prototype.has = function (k) {
return !!find(this._data, k);
};
PseudoMap.prototype.get = function (k) {
var res = find(this._data, k);
return res && res.value;
};
PseudoMap.prototype.set = function (k, v) {
set$1(this._data, k, v);
};
PseudoMap.prototype.delete = function (k) {
var res = find(this._data, k);
if (res) {
delete this._data[res._index];
this._data.size--;
}
};
PseudoMap.prototype.clear = function () {
var data = Object.create(null);
data.size = 0;
Object.defineProperty(this, '_data', {
value: data,
enumerable: false,
configurable: true,
writable: false
});
};
Object.defineProperty(PseudoMap.prototype, 'size', {
get: function get() {
return this._data.size;
},
set: function set(n) {},
enumerable: true,
configurable: true
});
PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
throw new Error('iterators are not implemented in this version');
}; // Either identical, or both NaN
function same(a, b) {
return a === b || a !== a && b !== b;
}
function Entry$1(k, v, i) {
this.key = k;
this.value = v;
this._index = i;
}
function find(data, k) {
for (var i = 0, s = '_' + k, key = s; hasOwnProperty$1.call(data, key); key = s + i++) {
if (same(data[key].key, k)) return data[key];
}
}
function set$1(data, k, v) {
for (var i = 0, s = '_' + k, key = s; hasOwnProperty$1.call(data, key); key = s + i++) {
if (same(data[key].key, k)) {
data[key].value = v;
return;
}
}
data.size++;
data[key] = new Entry$1(k, v, key);
}
var map = createCommonjsModule(function (module) {
if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
module.exports = Map;
} else {
module.exports = pseudomap;
}
});
var yallist = Yallist;
Yallist.Node = Node;
Yallist.create = Yallist;
function Yallist(list) {
var self = this;
if (!(self instanceof Yallist)) {
self = new Yallist();
}
self.tail = null;
self.head = null;
self.length = 0;
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item);
});
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i]);
}
}
return self;
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list');
}
var next = node.next;
var prev = node.prev;
if (next) {
next.prev = prev;
}
if (prev) {
prev.next = next;
}
if (node === this.head) {
this.head = next;
}
if (node === this.tail) {
this.tail = prev;
}
node.list.length--;
node.next = null;
node.prev = null;
node.list = null;
};
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var head = this.head;
node.list = this;
node.next = head;
if (head) {
head.prev = node;
}
this.head = node;
if (!this.tail) {
this.tail = node;
}
this.length++;
};
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var tail = this.tail;
node.list = this;
node.prev = tail;
if (tail) {
tail.next = node;
}
this.tail = node;
if (!this.head) {
this.head = node;
}
this.length++;
};
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i]);
}
return this.length;
};
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i]);
}
return this.length;
};
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined;
}
var res = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
this.length--;
return res;
};
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined;
}
var res = this.head.value;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
} else {
this.tail = null;
}
this.length--;
return res;
};
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this);
walker = walker.next;
}
};
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this);
walker = walker.prev;
}
};
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist();
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.next;
}
return res;
};
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist();
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.prev;
}
return res;
};
Yallist.prototype.reduce = function (fn, initial) {
var acc;
var walker = this.head;
if (arguments.length > 1) {
acc = initial;
} else if (this.head) {
walker = this.head.next;
acc = this.head.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i);
walker = walker.next;
}
return acc;
};
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc;
var walker = this.tail;
if (arguments.length > 1) {
acc = initial;
} else if (this.tail) {
walker = this.tail.prev;
acc = this.tail.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i);
walker = walker.prev;
}
return acc;
};
Yallist.prototype.toArray = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.next;
}
return arr;
};
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.prev;
}
return arr;
};
Yallist.prototype.slice = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next;
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value);
}
return ret;
};
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev;
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value);
}
return ret;
};
Yallist.prototype.reverse = function () {
var head = this.head;
var tail = this.tail;
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev;
walker.prev = walker.next;
walker.next = p;
}
this.head = tail;
this.tail = head;
return this;
};
function push(self, item) {
self.tail = new Node(item, self.tail, null, self);
if (!self.head) {
self.head = self.tail;
}
self.length++;
}
function unshift(self, item) {
self.head = new Node(item, null, self.head, self);
if (!self.tail) {
self.tail = self.head;
}
self.length++;
}
function Node(value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list);
}
this.list = list;
this.value = value;
if (prev) {
prev.next = this;
this.prev = prev;
} else {
this.prev = null;
}
if (next) {
next.prev = this;
this.next = next;
} else {
this.next = null;
}
}
var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
// or a fakey-fake PseudoMap in older versions.
// A linked list to keep track of recently-used-ness
// use symbols if possible, otherwise just _props
var hasSymbol = typeof Symbol === 'function';
var makeSymbol;
if (hasSymbol) {
makeSymbol = function makeSymbol(key) {
return Symbol.for(key);
};
} else {
makeSymbol = function makeSymbol(key) {
return '_' + key;
};
}
var MAX = makeSymbol('max');
var LENGTH = makeSymbol('length');
var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
var ALLOW_STALE = makeSymbol('allowStale');
var MAX_AGE = makeSymbol('maxAge');
var DISPOSE = makeSymbol('dispose');
var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
var LRU_LIST = makeSymbol('lruList');
var CACHE = makeSymbol('cache');
function naiveLength() {
return 1;
} // lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
function LRUCache(options) {
if (!(this instanceof LRUCache)) {
return new LRUCache(options);
}
if (typeof options === 'number') {
options = {
max: options
};
}
if (!options) {
options = {};
}
var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
if (!max || !(typeof max === 'number') || max <= 0) {
this[MAX] = Infinity;
}
var lc = options.length || naiveLength;
if (typeof lc !== 'function') {
lc = naiveLength;
}
this[LENGTH_CALCULATOR] = lc;
this[ALLOW_STALE] = options.stale || false;
this[MAX_AGE] = options.maxAge || 0;
this[DISPOSE] = options.dispose;
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
this.reset();
} // resize the cache when the max changes.
Object.defineProperty(LRUCache.prototype, 'max', {
set: function set(mL) {
if (!mL || !(typeof mL === 'number') || mL <= 0) {
mL = Infinity;
}
this[MAX] = mL;
trim(this);
},
get: function get() {
return this[MAX];
},
enumerable: true
});
Object.defineProperty(LRUCache.prototype, 'allowStale', {
set: function set(allowStale) {
this[ALLOW_STALE] = !!allowStale;
},
get: function get() {
return this[ALLOW_STALE];
},
enumerable: true
});
Object.defineProperty(LRUCache.prototype, 'maxAge', {
set: function set(mA) {
if (!mA || !(typeof mA === 'number') || mA < 0) {
mA = 0;
}
this[MAX_AGE] = mA;
trim(this);
},
get: function get() {
return this[MAX_AGE];
},
enumerable: true
}); // resize the cache when the lengthCalculator changes.
Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
set: function set(lC) {
if (typeof lC !== 'function') {
lC = naiveLength;
}
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC;
this[LENGTH] = 0;
this[LRU_LIST].forEach(function (hit) {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
this[LENGTH] += hit.length;
}, this);
}
trim(this);
},
get: function get() {
return this[LENGTH_CALCULATOR];
},
enumerable: true
});
Object.defineProperty(LRUCache.prototype, 'length', {
get: function get() {
return this[LENGTH];
},
enumerable: true
});
Object.defineProperty(LRUCache.prototype, 'itemCount', {
get: function get() {
return this[LRU_LIST].length;
},
enumerable: true
});
LRUCache.prototype.rforEach = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this[LRU_LIST].tail; walker !== null;) {
var prev = walker.prev;
forEachStep(this, fn, walker, thisp);
walker = prev;
}
};
function forEachStep(self, fn, node, thisp) {
var hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) {
hit = undefined;
}
}
if (hit) {
fn.call(thisp, hit.value, hit.key, self);
}
}
LRUCache.prototype.forEach = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this[LRU_LIST].head; walker !== null;) {
var next = walker.next;
forEachStep(this, fn, walker, thisp);
walker = next;
}
};
LRUCache.prototype.keys = function () {
return this[LRU_LIST].toArray().map(function (k) {
return k.key;
}, this);
};
LRUCache.prototype.values = function () {
return this[LRU_LIST].toArray().map(function (k) {
return k.value;
}, this);
};
LRUCache.prototype.reset = function () {
if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
this[LRU_LIST].forEach(function (hit) {
this[DISPOSE](hit.key, hit.value);
}, this);
}
this[CACHE] = new map(); // hash of items by key
this[LRU_LIST] = new yallist(); // list of items in order of use recency
this[LENGTH] = 0; // length of items in the list
};
LRUCache.prototype.dump = function () {
return this[LRU_LIST].map(function (hit) {
if (!isStale(this, hit)) {
return {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
};
}
}, this).toArray().filter(function (h) {
return h;
});
};
LRUCache.prototype.dumpLru = function () {
return this[LRU_LIST];
};
LRUCache.prototype.inspect = function (n, opts) {
var str = 'LRUCache {';
var extras = false;
var as = this[ALLOW_STALE];
if (as) {
str += '\n allowStale: true';
extras = true;
}
var max = this[MAX];
if (max && max !== Infinity) {
if (extras) {
str += ',';
}
str += '\n max: ' + util.inspect(max, opts);
extras = true;
}
var maxAge = this[MAX_AGE];
if (maxAge) {
if (extras) {
str += ',';
}
str += '\n maxAge: ' + util.inspect(maxAge, opts);
extras = true;
}
var lc = this[LENGTH_CALCULATOR];
if (lc && lc !== naiveLength) {
if (extras) {
str += ',';
}
str += '\n length: ' + util.inspect(this[LENGTH], opts);
extras = true;
}
var didFirst = false;
this[LRU_LIST].forEach(function (item) {
if (didFirst) {
str += ',\n ';
} else {
if (extras) {
str += ',\n';
}
didFirst = true;
str += '\n ';
}
var key = util.inspect(item.key).split('\n').join('\n ');
var val = {
value: item.value
};
if (item.maxAge !== maxAge) {
val.maxAge = item.maxAge;
}
if (lc !== naiveLength) {
val.length = item.length;
}
if (isStale(this, item)) {
val.stale = true;
}
val = util.inspect(val, opts).split('\n').join('\n ');
str += key + ' => ' + val;
});
if (didFirst || extras) {
str += '\n';
}
str += '}';
return str;
};
LRUCache.prototype.set = function (key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE];
var now = maxAge ? Date.now() : 0;
var len = this[LENGTH_CALCULATOR](value, key);
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key));
return false;
}
var node = this[CACHE].get(key);
var item = node.value; // dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET]) {
this[DISPOSE](key, item.value);
}
}
item.now = now;
item.maxAge = maxAge;
item.value = value;
this[LENGTH] += len - item.length;
item.length = len;
this.get(key);
trim(this);
return true;
}
var hit = new Entry(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE]) {
this[DISPOSE](key, value);
}
return false;
}
this[LENGTH] += hit.length;
this[LRU_LIST].unshift(hit);
this[CACHE].set(key, this[LRU_LIST].head);
trim(this);
return true;
};
LRUCache.prototype.has = function (key) {
if (!this[CACHE].has(key)) return false;
var hit = this[CACHE].get(key).value;
if (isStale(this, hit)) {
return false;
}
return true;
};
LRUCache.prototype.get = function (key) {
return get(this, key, true);
};
LRUCache.prototype.peek = function (key) {
return get(this, key, false);
};
LRUCache.prototype.pop = function () {
var node = this[LRU_LIST].tail;
if (!node) return null;
del(this, node);
return node.value;
};
LRUCache.prototype.del = function (key) {
del(this, this[CACHE].get(key));
};
LRUCache.prototype.load = function (arr) {
// reset the cache
this.reset();
var now = Date.now(); // A previous serialized cache has the most recent items first
for (var l = arr.length - 1; l >= 0; l--) {
var hit = arr[l];
var expiresAt = hit.e || 0;
if (expiresAt === 0) {
// the item was created without expiration in a non aged cache
this.set(hit.k, hit.v);
} else {
var maxAge = expiresAt - now; // dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge);
}
}
}
};
LRUCache.prototype.prune = function () {
var self = this;
this[CACHE].forEach(function (value, key) {
get(self, key, false);
});
};
function get(self, key, doUse) {
var node = self[CACHE].get(key);
if (node) {
var hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) hit = undefined;
} else {
if (doUse) {
self[LRU_LIST].unshiftNode(node);
}
}
if (hit) hit = hit.value;
}
return hit;
}
function isStale(self, hit) {
if (!hit || !hit.maxAge && !self[MAX_AGE]) {
return false;
}
var stale = false;
var diff = Date.now() - hit.now;
if (hit.maxAge) {
stale = diff > hit.maxAge;
} else {
stale = self[MAX_AGE] && diff > self[MAX_AGE];
}
return stale;
}
function trim(self) {
if (self[LENGTH] > self[MAX]) {
for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
var prev = walker.prev;
del(self, walker);
walker = prev;
}
}
}
function del(self, node) {
if (node) {
var hit = node.value;
if (self[DISPOSE]) {
self[DISPOSE](hit.key, hit.value);
}
self[LENGTH] -= hit.length;
self[CACHE].delete(hit.key);
self[LRU_LIST].removeNode(node);
}
} // classy, since V8 prefers predictable objects.
function Entry(key, value, length, now, maxAge) {
this.key = key;
this.value = value;
this.length = length;
this.now = now;
this.maxAge = maxAge || 0;
}
var sigmund_1 = sigmund;
function sigmund(subject, maxSessions) {
maxSessions = maxSessions || 10;
var notes = [];
var analysis = '';
var RE = RegExp;
function psychoAnalyze(subject, session) {
if (session > maxSessions) return;
if (typeof subject === 'function' || typeof subject === 'undefined') {
return;
}
if (typeof subject !== 'object' || !subject || subject instanceof RE) {
analysis += subject;
return;
}
if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
notes.push(subject);
analysis += '{';
Object.keys(subject).forEach(function (issue, _, __) {
// pseudo-private values. skip those.
if (issue.charAt(0) === '_') return;
var to = typeof subject[issue];
if (to === 'function' || to === 'undefined') return;
analysis += issue;
psychoAnalyze(subject[issue], session + 1);
});
}
psychoAnalyze(subject, 0);
return analysis;
} // vim: set softtabstop=4 shiftwidth=4:
var fnmatch = createCommonjsModule(function (module, exports) {
// Based on minimatch.js by isaacs
var platform = typeof process === "object" ? process.platform : "win32";
if (module) module.exports = minimatch;else exports.minimatch = minimatch;
minimatch.Minimatch = Minimatch;
var cache = minimatch.cache = new lruCache({
max: 100
}),
GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
var qmark = "[^/]" // * => any number of characters
,
star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
,
twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
// followed by anything, any number of times.
,
twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
,
reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
function charSet(s) {
return s.split("").reduce(function (set, c) {
set[c] = true;
return set;
}, {});
} // normalizes slashes.
var slashSplit = /\/+/;
minimatch.monkeyPatch = monkeyPatch;
function monkeyPatch() {
var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
var orig = desc.value;
desc.value = function (p) {
if (p instanceof Minimatch) return p.match(this);
return orig.call(this, p);
};
Object.defineProperty(String.prototype, desc);
}
minimatch.filter = filter;
function filter(pattern, options) {
options = options || {};
return function (p, i, list) {
return minimatch(p, pattern, options);
};
}
function ext(a, b) {
a = a || {};
b = b || {};
var t = {};
Object.keys(b).forEach(function (k) {
t[k] = b[k];
});
Object.keys(a).forEach(function (k) {
t[k] = a[k];
});
return t;
}
minimatch.defaults = function (def) {
if (!def || !Object.keys(def).length) return minimatch;
var orig = minimatch;
var m = function minimatch(p, pattern, options) {
return orig.minimatch(p, pattern, ext(def, options));
};
m.Minimatch = function Minimatch(pattern, options) {
return new orig.Minimatch(pattern, ext(def, options));
};
return m;
};
Minimatch.defaults = function (def) {
if (!def || !Object.keys(def).length) return Minimatch;
return minimatch.defaults(def).Minimatch;
};
function minimatch(p, pattern, options) {
if (typeof pattern !== "string") {
throw new TypeError("glob pattern string required");
}
if (!options) options = {}; // shortcut: comments match nothing.
if (!options.nocomment && pattern.charAt(0) === "#") {
return false;
} // "" only matches ""
if (pattern.trim() === "") return p === "";
return new Minimatch(pattern, options).match(p);
}
function Minimatch(pattern, options) {
if (!(this instanceof Minimatch)) {
return new Minimatch(pattern, options, cache);
}
if (typeof pattern !== "string") {
throw new TypeError("glob pattern string required");
}
if (!options) options = {}; // windows: need to use /, not \
// On other platforms, \ is a valid (albeit bad) filename char.
if (platform === "win32") {
pattern = pattern.split("\\").join("/");
} // lru storage.
// these things aren't particularly big, but walking down the string
// and turning it into a regexp can get pretty costly.
var cacheKey = pattern + "\n" + sigmund_1(options);
var cached = minimatch.cache.get(cacheKey);
if (cached) return cached;
minimatch.cache.set(cacheKey, this);
this.options = options;
this.set = [];
this.pattern = pattern;
this.regexp = null;
this.negate = false;
this.comment = false;
this.empty = false; // make the set of regexps etc.
this.make();
}
Minimatch.prototype.make = make;
function make() {
// don't do it more than once.
if (this._made) return;
var pattern = this.pattern;
var options = this.options; // empty patterns and comments match nothing.
if (!options.nocomment && pattern.charAt(0) === "#") {
this.comment = true;
return;
}
if (!pattern) {
this.empty = true;
return;
} // step 1: figure out negation, etc.
this.parseNegate(); // step 2: expand braces
var set = this.globSet = this.braceExpand();
if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
// matching patterns.
// These will be regexps, except in the case of "**", which is
// set to the GLOBSTAR object for globstar behavior,
// and will not contain any / characters
set = this.globParts = set.map(function (s) {
return s.split(slashSplit);
});
if (options.debug) console.error(this.pattern, set); // glob --> regexps
set = set.map(function (s, si, set) {
return s.map(this.parse, this);
}, this);
if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
set = set.filter(function (s) {
return -1 === s.indexOf(false);
});
if (options.debug) console.error(this.pattern, set);
this.set = set;
}
Minimatch.prototype.parseNegate = parseNegate;
function parseNegate() {
var pattern = this.pattern,
negate = false,
options = this.options,
negateOffset = 0;
if (options.nonegate) return;
for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
negate = !negate;
negateOffset++;
}
if (negateOffset) this.pattern = pattern.substr(negateOffset);
this.negate = negate;
} // Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
return new Minimatch(pattern, options).braceExpand();
};
Minimatch.prototype.braceExpand = braceExpand;
function braceExpand(pattern, options) {
options = options || this.options;
pattern = typeof pattern === "undefined" ? this.pattern : pattern;
if (typeof pattern === "undefined") {
throw new Error("undefined pattern");
}
if (options.nobrace || !pattern.match(/\{.*\}/)) {
// shortcut. no need to expand.
return [pattern];
}
var escaping = false; // examples and comments refer to this crazy pattern:
// a{b,c{d,e},{f,g}h}x{y,z}
// expected:
// abxy
// abxz
// acdxy
// acdxz
// acexy
// acexz
// afhxy
// afhxz
// aghxy
// aghxz
// everything before the first \{ is just a prefix.
// So, we pluck that off, and work with the rest,
// and then prepend it to everything we find.
if (pattern.charAt(0) !== "{") {
// console.error(pattern)
var prefix = null;
for (var i = 0, l = pattern.length; i < l; i++) {
var c = pattern.charAt(i); // console.error(i, c)
if (c === "\\") {
escaping = !escaping;
} else if (c === "{" && !escaping) {
prefix = pattern.substr(0, i);
break;
}
} // actually no sets, all { were escaped.
if (prefix === null) {
// console.error("no sets")
return [pattern];
}
var tail = braceExpand(pattern.substr(i), options);
return tail.map(function (t) {
return prefix + t;
});
} // now we have something like:
// {b,c{d,e},{f,g}h}x{y,z}
// walk through the set, expanding each part, until
// the set ends. then, we'll expand the suffix.
// If the set only has a single member, then'll put the {} back
// first, handle numeric sets, since they're easier
var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
if (numset) {
// console.error("numset", numset[1], numset[2])
var suf = braceExpand(pattern.substr(numset[0].length), options),
start = +numset[1],
end = +numset[2],
inc = start > end ? -1 : 1,
set = [];
for (var i = start; i != end + inc; i += inc) {
// append all the suffixes
for (var ii = 0, ll = suf.length; ii < ll; ii++) {
set.push(i + suf[ii]);
}
}
return set;
} // ok, walk through the set
// We hope, somewhat optimistically, that there
// will be a } at the end.
// If the closing brace isn't found, then the pattern is
// interpreted as braceExpand("\\" + pattern) so that
// the leading \{ will be interpreted literally.
var i = 1 // skip the \{
,
depth = 1,
set = [],
member = "",
sawEnd = false,
escaping = false;
function addMember() {
set.push(member);
member = "";
} // console.error("Entering for")
FOR: for (i = 1, l = pattern.length; i < l; i++) {
var c = pattern.charAt(i); // console.error("", i, c)
if (escaping) {
escaping = false;
member += "\\" + c;
} else {
switch (c) {
case "\\":
escaping = true;
continue;
case "{":
depth++;
member += "{";
continue;
case "}":
depth--; // if this closes the actual set, then we're done
if (depth === 0) {
addMember(); // pluck off the close-brace
i++;
break FOR;
} else {
member += c;
continue;
}
case ",":
if (depth === 1) {
addMember();
} else {
member += c;
}
continue;
default:
member += c;
continue;
} // switch
} // else
} // for
// now we've either finished the set, and the suffix is
// pattern.substr(i), or we have *not* closed the set,
// and need to escape the leading brace
if (depth !== 0) {
// console.error("didn't close", pattern)
return braceExpand("\\" + pattern, options);
} // x{y,z} -> ["xy", "xz"]
// console.error("set", set)
// console.error("suffix", pattern.substr(i))
var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
// [["b"], ["cd", "ce"], ["fh", "gh"]]
var addBraces = set.length === 1; // console.error("set pre-expanded", set)
set = set.map(function (p) {
return braceExpand(p, options);
}); // console.error("set expanded", set)
// [["b"], ["cd", "ce"], ["fh", "gh"]] ->
// ["b", "cd", "ce", "fh", "gh"]
set = set.reduce(function (l, r) {
return l.concat(r);
});
if (addBraces) {
set = set.map(function (s) {
return "{" + s + "}";
});
} // now attach the suffixes.
var ret = [];
for (var i = 0, l = set.length; i < l; i++) {
for (var ii = 0, ll = suf.length; ii < ll; ii++) {
ret.push(set[i] + suf[ii]);
}
}
return ret;
} // parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion. Otherwise, any series
// of * is equivalent to a single *. Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse;
var SUBPARSE = {};
function parse(pattern, isSub) {
var options = this.options; // shortcuts
if (!options.noglobstar && pattern === "**") return GLOBSTAR;
if (pattern === "") return "";
var re = "",
hasMagic = !!options.nocase,
escaping = false // ? => one single character
,
patternListStack = [],
plType,
stateChar,
inClass = false,
reClassStart = -1,
classStart = -1 // . and .. never match anything that doesn't start with .,
// even when options.dot is set.
,
patternStart = pattern.charAt(0) === "." ? "" // anything
// not (start or / followed by . or .. followed by / or end)
: options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
function clearStateChar() {
if (stateChar) {
// we had some state-tracking character
// that wasn't consumed by this pass.
switch (stateChar) {
case "*":
re += star;
hasMagic = true;
break;
case "?":
re += qmark;
hasMagic = true;
break;
default:
re += "\\" + stateChar;
break;
}
stateChar = false;
}
}
for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
if (options.debug) {
console.error("%s\t%s %s %j", pattern, i, re, c);
} // skip over any that are escaped.
if (escaping && reSpecials[c]) {
re += "\\" + c;
escaping = false;
continue;
}
SWITCH: switch (c) {
case "/":
// completely not allowed, even escaped.
// Should already be path-split by now.
return false;
case "\\":
clearStateChar();
escaping = true;
continue;
// the various stateChar values
// for the "extglob" stuff.
case "?":
case "*":
case "+":
case "@":
case "!":
if (options.debug) {
console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
} // all of those are literals inside a class, except that
// the glob [!a] means [^a] in regexp
if (inClass) {
if (c === "!" && i === classStart + 1) c = "^";
re += c;
continue;
} // if we already have a stateChar, then it means
// that there was something like ** or +? in there.
// Handle the stateChar, then proceed with this one.
clearStateChar();
stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
// just clear the statechar *now*, rather than even diving into
// the patternList stuff.
if (options.noext) clearStateChar();
continue;
case "(":
if (inClass) {
re += "(";
continue;
}
if (!stateChar) {
re += "\\(";
continue;
}
plType = stateChar;
patternListStack.push({
type: plType,
start: i - 1,
reStart: re.length
}); // negation is (?:(?!js)[^/]*)
re += stateChar === "!" ? "(?:(?!" : "(?:";
stateChar = false;
continue;
case ")":
if (inClass || !patternListStack.length) {
re += "\\)";
continue;
}
hasMagic = true;
re += ")";
plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
// The others are (?:)
switch (plType) {
case "!":
re += "[^/]*?)";
break;
case "?":
case "+":
case "*":
re += plType;
case "@":
break;
// the default anyway
}
continue;
case "|":
if (inClass || !patternListStack.length || escaping) {
re += "\\|";
escaping = false;
continue;
}
re += "|";
continue;
// these are mostly the same in regexp and glob
case "[":
// swallow any state-tracking char before the [
clearStateChar();
if (inClass) {
re += "\\" + c;
continue;
}
inClass = true;
classStart = i;
reClassStart = re.length;
re += c;
continue;
case "]":
// a right bracket shall lose its special
// meaning and represent itself in
// a bracket expression if it occurs
// first in the list. -- POSIX.2 2.8.3.2
if (i === classStart + 1 || !inClass) {
re += "\\" + c;
escaping = false;
continue;
} // finish up the class.
hasMagic = true;
inClass = false;
re += c;
continue;
default:
// swallow any state char that wasn't consumed
clearStateChar();
if (escaping) {
// no need
escaping = false;
} else if (reSpecials[c] && !(c === "^" && inClass)) {
re += "\\";
}
re += c;
} // switch
} // for
// handle the case where we left a class open.
// "[abc" is valid, equivalent to "\[abc"
if (inClass) {
// split where the last [ was, and escape it
// this is a huge pita. We now have to re-walk
// the contents of the would-be class to re-translate
// any characters that were passed through as-is
var cs = pattern.substr(classStart + 1),
sp = this.parse(cs, SUBPARSE);
re = re.substr(0, reClassStart) + "\\[" + sp[0];
hasMagic = hasMagic || sp[1];
} // handle the case where we had a +( thing at the *end*
// of the pattern.
// each pattern list stack adds 3 chars, and we need to go through
// and escape any | chars that were passed through as-is for the regexp.
// Go through and escape them, taking care not to double-escape any
// | chars that were already escaped.
var pl;
while (pl = patternListStack.pop()) {
var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
if (!$2) {
// the | isn't already escaped, so escape it.
$2 = "\\";
} // need to escape all those slashes *again*, without escaping the
// one that we need for escaping the | character. As it works out,
// escaping an even number of slashes can be done by simply repeating
// it exactly after itself. That's why this trick works.
//
// I am sorry that you have to see this.
return $1 + $1 + $2 + "|";
}); // console.error("tail=%j\n %s", tail, tail)
var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
hasMagic = true;
re = re.slice(0, pl.reStart) + t + "\\(" + tail;
} // handle trailing things that only matter at the very end.
clearStateChar();
if (escaping) {
// trailing \\
re += "\\\\";
} // only need to apply the nodot start if the re starts with
// something that could conceivably capture a dot
var addPatternStart = false;
switch (re.charAt(0)) {
case ".":
case "[":
case "(":
addPatternStart = true;
} // if the re is not "" at this point, then we need to make sure
// it doesn't match against an empty path part.
// Otherwise a/* will match a/, which it should not.
if (re !== "" && hasMagic) re = "(?=.)" + re;
if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
if (isSub === SUBPARSE) {
return [re, hasMagic];
} // skip the regexp for non-magical patterns
// unescape anything in it, though, so that it'll be
// an exact match against a file etc.
if (!hasMagic) {
return globUnescape(pattern);
}
var flags = options.nocase ? "i" : "",
regExp = new RegExp("^" + re + "$", flags);
regExp._glob = pattern;
regExp._src = re;
return regExp;
}
minimatch.makeRe = function (pattern, options) {
return new Minimatch(pattern, options || {}).makeRe();
};
Minimatch.prototype.makeRe = makeRe;
function makeRe() {
if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
var set = this.set;
if (!set.length) return this.regexp = false;
var options = this.options;
var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
flags = options.nocase ? "i" : "";
var re = set.map(function (pattern) {
return pattern.map(function (p) {
return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
}).join("\\\/");
}).join("|"); // must match entire pattern
// ending in a * or ** will make it less strict.
re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
if (this.negate) re = "^(?!" + re + ").*$";
try {
return this.regexp = new RegExp(re, flags);
} catch (ex) {
return this.regexp = false;
}
}
minimatch.match = function (list, pattern, options) {
var mm = new Minimatch(pattern, options);
list = list.filter(function (f) {
return mm.match(f);
});
if (options.nonull && !list.length) {
list.push(pattern);
}
return list;
};
Minimatch.prototype.match = match;
function match(f, partial) {
// console.error("match", f, this.pattern)
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) return false;
if (this.empty) return f === "";
if (f === "/" && partial) return true;
var options = this.options; // windows: need to use /, not \
// On other platforms, \ is a valid (albeit bad) filename char.
if (platform === "win32") {
f = f.split("\\").join("/");
} // treat the test path as a set of pathparts.
f = f.split(slashSplit);
if (options.debug) {
console.error(this.pattern, "split", f);
} // just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
var set = this.set; // console.error(this.pattern, "set", set)
for (var i = 0, l = set.length; i < l; i++) {
var pattern = set[i];
var hit = this.matchOne(f, pattern, partial);
if (hit) {
if (options.flipNegate) return true;
return !this.negate;
}
} // didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) return false;
return this.negate;
} // set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
var options = this.options;
if (options.debug) {
console.error("matchOne", {
"this": this,
file: file,
pattern: pattern
});
}
if (options.matchBase && pattern.length === 1) {
file = path.basename(file.join("/")).split("/");
}
if (options.debug) {
console.error("matchOne", file.length, pattern.length);
}
for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
if (options.debug) {
console.error("matchOne loop");
}
var p = pattern[pi],
f = file[fi];
if (options.debug) {
console.error(pattern, p, f);
} // should be impossible.
// some invalid regexp stuff in the set.
if (p === false) return false;
if (p === GLOBSTAR) {
if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi,
pr = pi + 1;
if (pr === pl) {
if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
}
return true;
} // ok, let's see if we can swallow whatever we can.
WHILE: while (fr < fl) {
var swallowee = file[fr];
if (options.debug) {
console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
} // XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
return true;
} else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
break WHILE;
} // ** swallows a segment, and continue.
if (options.debug) console.error('globstar swallow a segment, and continue');
fr++;
}
} // no match was found.
// However, in partial mode, we can't say this is necessarily over.
// If there's more *pattern* left, then
if (partial) {
// ran out of file
// console.error("\n>>> no match, partial?", file, fr, pattern, pr)
if (fr === fl) return true;
}
return false;
} // something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
var hit;
if (typeof p === "string") {
if (options.nocase) {
hit = f.toLowerCase() === p.toLowerCase();
} else {
hit = f === p;
}
if (options.debug) {
console.error("string match", p, f, hit);
}
} else {
hit = f.match(p);
if (options.debug) {
console.error("pattern match", p, f, hit);
}
}
if (!hit) return false;
} // Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true;
} else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial;
} else if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
var emptyFileEnd = fi === fl - 1 && file[fi] === "";
return emptyFileEnd;
} // should be unreachable.
throw new Error("wtf?");
}; // replace stuff like \* with *
function globUnescape(s) {
return s.replace(/\\(.)/g, "$1");
}
function regExpEscape(s) {
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
});
var ini = createCommonjsModule(function (module, exports) {
"use strict"; // Based on iniparser by shockie
var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : new P(function (resolve) {
resolve(result.value);
}).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = commonjsGlobal && commonjsGlobal.__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) {
try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
};
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* define the possible values:
* section: [section]
* param: key=value
* comment: ;this is a comment
*/
var regex = {
section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
comment: /^\s*[#;].*$/
};
/**
* Parses an .ini file
* @param file The location of the .ini file
*/
function parse(file) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2
/*return*/
, new Promise(function (resolve, reject) {
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
reject(err);
return;
}
resolve(parseString(data));
});
})];
});
});
}
exports.parse = parse;
function parseSync(file) {
return parseString(fs.readFileSync(file, 'utf8'));
}
exports.parseSync = parseSync;
function parseString(data) {
var sectionBody = {};
var sectionName = null;
var value = [[sectionName, sectionBody]];
var lines = data.split(/\r\n|\r|\n/);
lines.forEach(function (line) {
var match;
if (regex.comment.test(line)) {
return;
}
if (regex.param.test(line)) {
match = line.match(regex.param);
sectionBody[match[1]] = match[2];
} else if (regex.section.test(line)) {
match = line.match(regex.section);
sectionName = match[1];
sectionBody = {};
value.push([sectionName, sectionBody]);
}
});
return value;
}
exports.parseString = parseString;
});
unwrapExports(ini);
var name$1 = "editorconfig";
var version$3 = "0.15.0";
var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
var keywords = ["editorconfig", "core"];
var main$1 = "index.js";
var bin$1 = {
"editorconfig": "bin/editorconfig"
};
var contributors = ["Hong Xu (topbug.net)", "Jed Mao (https://github.com/jedmao/)", "Trey Hunner (http://treyhunner.com)"];
var directories = {
"bin": "./bin",
"lib": "./lib"
};
var scripts$1 = {
"clean": "rimraf dist",
"prebuild": "npm run clean",
"build": "tsc",
"pretest": "npm run lint && npm run build && npm run copy && cmake .",
"test": "ctest .",
"pretest:ci": "npm run pretest",
"test:ci": "ctest -VV --output-on-failure .",
"lint": "npm run eclint && npm run tslint",
"eclint": "eclint check --indent_size ignore \"src/**\"",
"tslint": "tslint --project tslint.json",
"copy": "cpy package.json .npmignore LICENSE README.md CHANGELOG.md dist && cpy src/bin/* dist/bin && cpy src/lib/fnmatch*.* dist/lib",
"prepub": "npm run lint && npm run build && npm run copy",
"pub": "npm publish ./dist"
};
var repository$1 = {
"type": "git",
"url": "git://github.com/editorconfig/editorconfig-core-js.git"
};
var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
var author$1 = "EditorConfig Team";
var license$1 = "MIT";
var dependencies$1 = {
"@types/commander": "^2.11.0",
"@types/semver": "^5.4.0",
"commander": "^2.11.0",
"lru-cache": "^4.1.1",
"semver": "^5.4.1",
"sigmund": "^1.0.1"
};
var devDependencies$1 = {
"@types/mocha": "^2.2.43",
"cpy-cli": "^1.0.1",
"eclint": "^2.4.3",
"mocha": "^4.0.1",
"rimraf": "^2.6.2",
"should": "^13.1.2",
"tslint": "^5.7.0",
"typescript": "^2.5.3"
};
var _package$2 = {
name: name$1,
version: version$3,
description: description$1,
keywords: keywords,
main: main$1,
bin: bin$1,
contributors: contributors,
directories: directories,
scripts: scripts$1,
repository: repository$1,
bugs: bugs,
author: author$1,
license: license$1,
dependencies: dependencies$1,
devDependencies: devDependencies$1
};
var _package$3 = Object.freeze({
name: name$1,
version: version$3,
description: description$1,
keywords: keywords,
main: main$1,
bin: bin$1,
contributors: contributors,
directories: directories,
scripts: scripts$1,
repository: repository$1,
bugs: bugs,
author: author$1,
license: license$1,
dependencies: dependencies$1,
devDependencies: devDependencies$1,
default: _package$2
});
var pkg = ( _package$3 && _package$2 ) || _package$3;
var editorconfig = createCommonjsModule(function (module, exports) {
"use strict";
var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : new P(function (resolve) {
resolve(result.value);
}).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = commonjsGlobal && commonjsGlobal.__generator || function (thisArg, body) {
var _ = {
label: 0,
sent: function sent() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) {
try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseString = ini.parseString; // tslint:disable-next-line:no-var-requires
var knownProps = {
end_of_line: true,
indent_style: true,
indent_size: true,
insert_final_newline: true,
trim_trailing_whitespace: true,
charset: true
};
function fnmatch$$1(filepath, glob) {
var matchOptions = {
matchBase: true,
dot: true,
noext: true
};
glob = glob.replace(/\*\*/g, '{*,**/**/**}');
return fnmatch(filepath, glob, matchOptions);
}
function getConfigFileNames(filepath, options) {
var paths = [];
do {
filepath = path.dirname(filepath);
paths.push(path.join(filepath, options.config));
} while (filepath !== options.root);
return paths;
}
function processMatches(matches, version) {
// Set indent_size to 'tab' if indent_size is unspecified and
// indent_style is set to 'tab'.
if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver$3.gte(version, '0.10.0')) {
matches.indent_size = 'tab';
} // Set tab_width to indent_size if indent_size is specified and
// tab_width is unspecified
if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
matches.tab_width = matches.indent_size;
} // Set indent_size to tab_width if indent_size is 'tab'
if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
matches.indent_size = matches.tab_width;
}
return matches;
}
function processOptions(options, filepath) {
if (options === void 0) {
options = {};
}
return {
config: options.config || '.editorconfig',
version: options.version || pkg.version,
root: path.resolve(options.root || path.parse(filepath).root)
};
}
function buildFullGlob(pathPrefix, glob) {
switch (glob.indexOf('/')) {
case -1:
glob = '**/' + glob;
break;
case 0:
glob = glob.substring(1);
break;
default:
break;
}
return path.join(pathPrefix, glob);
}
function extendProps(props, options) {
if (props === void 0) {
props = {};
}
if (options === void 0) {
options = {};
}
for (var key in options) {
if (options.hasOwnProperty(key)) {
var value = options[key];
var key2 = key.toLowerCase();
var value2 = value;
if (knownProps[key2]) {
value2 = value.toLowerCase();
}
try {
value2 = JSON.parse(value);
} catch (e) {}
if (typeof value === 'undefined' || value === null) {
// null and undefined are values specific to JSON (no special meaning
// in editorconfig) & should just be returned as regular strings.
value2 = String(value);
}
props[key2] = value2;
}
}
return props;
}
function parseFromConfigs(configs, filepath, options) {
return processMatches(configs.reverse().reduce(function (matches, file) {
var pathPrefix = path.dirname(file.name);
file.contents.forEach(function (section) {
var glob = section[0];
var options2 = section[1];
if (!glob) {
return;
}
var fullGlob = buildFullGlob(pathPrefix, glob);
if (!fnmatch$$1(filepath, fullGlob)) {
return;
}
matches = extendProps(matches, options2);
});
return matches;
}, {}), options.version);
}
function getConfigsForFiles(files) {
var configs = [];
for (var i in files) {
if (files.hasOwnProperty(i)) {
var file = files[i];
var contents = ini.parseString(file.contents);
configs.push({
name: file.name,
contents: contents
});
if ((contents[0][1].root || '').toLowerCase() === 'true') {
break;
}
}
}
return configs;
}
function readConfigFiles(filepaths) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2
/*return*/
, Promise.all(filepaths.map(function (name) {
return new Promise(function (resolve) {
fs.readFile(name, 'utf8', function (err, data) {
resolve({
name: name,
contents: err ? '' : data
});
});
});
}))];
});
});
}
function readConfigFilesSync(filepaths) {
var files = [];
var file;
filepaths.forEach(function (filepath) {
try {
file = fs.readFileSync(filepath, 'utf8');
} catch (e) {
file = '';
}
files.push({
name: filepath,
contents: file
});
});
return files;
}
function opts(filepath, options) {
if (options === void 0) {
options = {};
}
var resolvedFilePath = path.resolve(filepath);
return [resolvedFilePath, processOptions(options, resolvedFilePath)];
}
function parseFromFiles(filepath, files, options) {
if (options === void 0) {
options = {};
}
return __awaiter(this, void 0, void 0, function () {
var _a, resolvedFilePath, processedOptions;
return __generator(this, function (_b) {
_a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
return [2
/*return*/
, files.then(getConfigsForFiles).then(function (configs) {
return parseFromConfigs(configs, resolvedFilePath, processedOptions);
})];
});
});
}
exports.parseFromFiles = parseFromFiles;
function parseFromFilesSync(filepath, files, options) {
if (options === void 0) {
options = {};
}
var _a = opts(filepath, options),
resolvedFilePath = _a[0],
processedOptions = _a[1];
return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
}
exports.parseFromFilesSync = parseFromFilesSync;
function parse(_filepath, _options) {
if (_options === void 0) {
_options = {};
}
return __awaiter(this, void 0, void 0, function () {
var _a, resolvedFilePath, processedOptions, filepaths;
return __generator(this, function (_b) {
_a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
return [2
/*return*/
, readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
return parseFromConfigs(configs, resolvedFilePath, processedOptions);
})];
});
});
}
exports.parse = parse;
function parseSync(_filepath, _options) {
if (_options === void 0) {
_options = {};
}
var _a = opts(_filepath, _options),
resolvedFilePath = _a[0],
processedOptions = _a[1];
var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
var files = readConfigFilesSync(filepaths);
return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
}
exports.parseSync = parseSync;
});
unwrapExports(editorconfig);
var editorconfigToPrettier = editorConfigToPrettier;
function editorConfigToPrettier(editorConfig) {
if (!editorConfig || Object.keys(editorConfig).length === 0) {
return null;
}
var 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";
var maybeParse = function maybeParse(filePath, config, parse) {
var root = findProjectRoot(path.dirname(path.resolve(filePath)));
return filePath && parse(filePath, {
root
});
};
var editorconfigAsyncNoCache = function editorconfigAsyncNoCache(filePath, config) {
return Promise.resolve(maybeParse(filePath, config, editorconfig.parse)).then(editorconfigToPrettier);
};
var editorconfigAsyncWithCache = mem(editorconfigAsyncNoCache);
var editorconfigSyncNoCache = function editorconfigSyncNoCache(filePath, config) {
return editorconfigToPrettier(maybeParse(filePath, config, editorconfig.parseSync));
};
var editorconfigSyncWithCache = mem(editorconfigSyncNoCache);
function getLoadFunction(opts) {
if (!opts.editorconfig) {
return function () {
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 resolveConfig_1 = createCommonjsModule(function (module) {
"use strict";
var getExplorerMemoized = mem(function (opts) {
return thirdParty$1.cosmiconfig("prettier", {
sync: opts.sync,
cache: opts.cache,
rcExtensions: true,
transform: function 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);
var loadOpts = {
cache: !!opts.useCache,
sync: !!sync,
editorconfig: !!opts.editorconfig
};
var load = getLoadFunction(loadOpts);
var loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
var arr = [load, loadEditorConfig].map(function (l) {
return l(filePath, opts.config);
});
var unwrapAndMerge = function unwrapAndMerge(arr) {
var result = arr[0];
var editorConfigured = arr[1];
var 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);
}
var resolveConfig = function resolveConfig(filePath, opts) {
return _resolveConfig(filePath, opts, false);
};
resolveConfig.sync = function (filePath, opts) {
return _resolveConfig(filePath, opts, true);
};
function clearCache() {
mem.clear(getExplorerMemoized);
resolveConfigEditorconfig.clearCache();
}
function resolveConfigFile(filePath) {
var load = getLoadFunction({
sync: false
});
return load(filePath).then(function (result) {
return result ? result.filepath : null;
});
}
resolveConfigFile.sync = function (filePath) {
var load = getLoadFunction({
sync: true
});
var result = load(filePath);
return result ? result.filepath : null;
};
function mergeOverrides(configResult, filePath) {
var options = Object.assign({}, configResult.config);
if (filePath && options.overrides) {
var relativeFilePath = path.relative(path.dirname(configResult.filepath), filePath);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = options.overrides[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var override = _step.value;
if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
Object.assign(options, override.options);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
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) {
var patternList = [].concat(patterns);
var excludedPatternList = [].concat(excludedPatterns || []);
var opts = {
matchBase: true
};
return patternList.some(function (pattern) {
return minimatch_1(filePath, pattern, opts);
}) && !excludedPatternList.some(function (excludedPattern) {
return minimatch_1(filePath, excludedPattern, opts);
});
}
module.exports = {
resolveConfig,
resolveConfigFile,
clearCache
};
});
var version = require$$0.version;
var getSupportInfo = support.getSupportInfo; // Luckily `opts` is always the 2nd argument
function _withPlugins(fn) {
return function () {
var args = Array.from(arguments);
var opts = args[1] || {};
args[1] = Object.assign({}, opts, {
plugins: loadPlugins_1(opts.plugins, opts.pluginSearchDirs)
});
return fn.apply(null, args);
};
}
function withPlugins(fn) {
var resultingFn = _withPlugins(fn);
if (fn.sync) {
resultingFn.sync = _withPlugins(fn.sync);
}
return resultingFn;
}
var formatWithCursor = withPlugins(core.formatWithCursor);
var prettier = {
formatWithCursor,
format(text, opts) {
return formatWithCursor(text, opts).formatted;
},
check: function check(text, opts) {
var formatted = formatWithCursor(text, opts).formatted;
return formatted === text;
},
doc,
resolveConfig: resolveConfig_1.resolveConfig,
resolveConfigFile: resolveConfig_1.resolveConfigFile,
clearConfigCache: resolveConfig_1.clearCache,
getFileInfo: withPlugins(getFileInfo_1),
getSupportInfo: withPlugins(getSupportInfo),
version,
util: utilShared,
/* istanbul ignore next */
__debug: {
parse: withPlugins(core.parse),
formatAST: withPlugins(core.formatAST),
formatDoc: withPlugins(core.formatDoc),
printToDoc: withPlugins(core.printToDoc),
printDocToString: withPlugins(core.printDocToString)
}
};
module.exports = prettier;