- !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
- // string literal with newlines
+ if (needsParens) {
+ parts.push("(");
+ }
- const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
- return group$a(concat$i(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$i([indent$e(concat$i(path.map(attr => concat$i([line$b, print(attr)]), "attributes"))), n.selfClosing ? line$b : bracketSameLine ? ">" : softline$a]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
- shouldBreak
- });
-}
+ const parametersDoc = printFunctionParameters$2(path, print, options,
+ /* expandArg */
+ false,
+ /* printTypeParams */
+ true); // The returnType is not wrapped in a TypeAnnotation, so the colon
+ // needs to be added separately.
-function printJsxClosingElement(path, options, print) {
- return concat$i(["", path.call(print, "name"), ">"]);
-}
+ const returnTypeDoc = node.returnType || node.predicate || node.typeAnnotation ? [isArrowFunctionTypeAnnotation ? " => " : ": ", print("returnType"), print("predicate"), print("typeAnnotation")] : "";
+ const shouldGroupParameters = shouldGroupFunctionParameters$2(node, returnTypeDoc);
+ parts.push(shouldGroupParameters ? group$p(parametersDoc) : parametersDoc);
-function printJsxOpeningClosingFragment(path, options
-/*, print*/
-) {
- const n = path.getValue();
- const hasComment = n.comments && n.comments.length;
- const hasOwnLineComment = hasComment && !n.comments.every(comment => isBlockComment$6(comment));
- const isOpeningFragment = n.type === "JSXOpeningFragment";
- return concat$i([isOpeningFragment ? "<" : "", indent$e(concat$i([hasOwnLineComment ? hardline$b : hasComment && !isOpeningFragment ? " " : "", printDanglingComments$5(path, options, true)])), hasOwnLineComment ? hardline$b : "", ">"]);
-}
+ if (returnTypeDoc) {
+ parts.push(returnTypeDoc);
+ }
-function printJsxElement(path, options, print) {
- const elem = printComments$1(path, () => printJsxElementInternal(path, options, print), options);
- return maybeWrapJSXElementInParens(path, elem, options);
-}
+ if (needsParens) {
+ parts.push(")");
+ }
-function printJsxEmptyExpression(path, options
-/*, print*/
-) {
- const n = path.getValue();
- const requiresHardline = n.comments && !n.comments.every(comment => isBlockComment$6(comment));
- return concat$i([printDanglingComments$5(path, options,
- /* sameIndent */
- !requiresHardline), requiresHardline ? hardline$b : ""]);
-} // `JSXSpreadAttribute` and `JSXSpreadChild`
+ return group$p(parts);
+} // `TSTupleType` and `TupleTypeAnnotation`
-function printJsxSpreadAttribute(path, options, print) {
- const n = path.getValue();
- return concat$i(["{", path.call(p => {
- const printed = concat$i(["...", print(p)]);
- const n = p.getValue();
+function printTupleType$2(path, options, print) {
+ const node = path.getValue();
+ const typesField = node.type === "TSTupleType" ? "elementTypes" : "types";
+ const hasRest = node[typesField].length > 0 && getLast$c(node[typesField]).type === "TSRestType";
+ return group$p(["[", indent$j([softline$j, printArrayItems$2(path, options, typesField, print)]), ifBreak$h(shouldPrintComma$7(options, "all") && !hasRest ? "," : ""), printDanglingComments$9(path, options,
+ /* sameIndent */
+ true), softline$j, "]"]);
+} // `TSIndexedAccessType`, `IndexedAccessType`, and `OptionalIndexedAccessType`
- if (!n.comments || !n.comments.length || !willPrintOwnComments$1(p)) {
- return printed;
- }
- return concat$i([indent$e(concat$i([softline$a, printComments$1(p, () => printed, options)])), softline$a]);
- }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
+function printIndexedAccessType$2(path, options, print) {
+ const node = path.getValue();
+ const leftDelimiter = node.type === "OptionalIndexedAccessType" && node.optional ? "?.[" : "[";
+ return [print("objectType"), leftDelimiter, print("indexType"), "]"];
}
-var jsx = {
- printJsxElement,
- printJsxAttribute,
- printJsxOpeningElement,
- printJsxClosingElement,
- printJsxOpeningClosingFragment,
- printJsxExpressionContainer,
- printJsxEmptyExpression,
- printJsxSpreadAttribute,
- // Alias
- printJsxSpreadChild: printJsxSpreadAttribute
+var typeAnnotation = {
+ printOpaqueType: printOpaqueType$1,
+ printTypeAlias: printTypeAlias$2,
+ printIntersectionType: printIntersectionType$2,
+ printUnionType: printUnionType$2,
+ printFunctionType: printFunctionType$2,
+ printTupleType: printTupleType$2,
+ printIndexedAccessType: printIndexedAccessType$2,
+ shouldHugType: shouldHugType$2
};
const {
- printDanglingComments: printDanglingComments$6
-} = comments;
+ printDanglingComments: printDanglingComments$8
+} = comments$4;
const {
builders: {
- concat: concat$j,
- join: join$7,
- line: line$c,
- hardline: hardline$c,
- softline: softline$b,
- group: group$b,
- indent: indent$f,
- ifBreak: ifBreak$7
+ join: join$k,
+ line: line$n,
+ hardline: hardline$r,
+ softline: softline$i,
+ group: group$o,
+ indent: indent$i,
+ ifBreak: ifBreak$g
}
-} = document;
+} = require$$7$3;
const {
- hasDanglingComments: hasDanglingComments$4,
- isTestCall: isTestCall$2,
- isBlockComment: isBlockComment$7,
- shouldPrintComma: shouldPrintComma$5
-} = utils$6;
+ isTestCall,
+ hasComment: hasComment$8,
+ CommentCheckFlags: CommentCheckFlags$8,
+ isTSXFile,
+ shouldPrintComma: shouldPrintComma$6,
+ getFunctionParameters: getFunctionParameters$1,
+ isObjectType
+} = utils$5;
const {
- shouldHugType: shouldHugType$2
+ createGroupIdMapper: createGroupIdMapper$1
+} = util$8;
+const {
+ shouldHugType: shouldHugType$1
} = typeAnnotation;
-const typeParametersGroupIds = new WeakMap();
-
-function getTypeParametersGroupId(node) {
- if (!typeParametersGroupIds.has(node)) {
- typeParametersGroupIds.set(node, Symbol("typeParameters"));
- }
-
- return typeParametersGroupIds.get(node);
-}
+const {
+ isArrowFunctionVariableDeclarator
+} = assignment;
+const getTypeParametersGroupId$2 = createGroupIdMapper$1("typeParameters");
-function printTypeParameters(path, options, print, paramsKey) {
- const n = path.getValue();
+function printTypeParameters$2(path, options, print, paramsKey) {
+ const node = path.getValue();
- if (!n[paramsKey]) {
+ if (!node[paramsKey]) {
return "";
} // for TypeParameterDeclaration typeParameters is a single node
- if (!Array.isArray(n[paramsKey])) {
- return path.call(print, paramsKey);
+ if (!Array.isArray(node[paramsKey])) {
+ return print(paramsKey);
}
const grandparent = path.getNode(2);
- const isParameterInTestCall = grandparent != null && isTestCall$2(grandparent);
- const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType$2(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType$2(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType$2(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation");
+ const isParameterInTestCall = grandparent && isTestCall(grandparent);
+ const isArrowFunctionVariable = path.match(node => !(node[paramsKey].length === 1 && isObjectType(node[paramsKey][0])), undefined, (node, name) => name === "typeAnnotation", node => node.type === "Identifier", isArrowFunctionVariableDeclarator);
+ const shouldInline = !isArrowFunctionVariable && (isParameterInTestCall || node[paramsKey].length === 0 || node[paramsKey].length === 1 && (node[paramsKey][0].type === "NullableTypeAnnotation" || shouldHugType$1(node[paramsKey][0])));
if (shouldInline) {
- return concat$j(["<", join$7(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(path, options), ">"]);
- }
+ return ["<", join$k(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(path, options), ">"];
+ } // Keep comma if the file extension is .tsx and
+ // has one type parameter that isn't extend with any types.
+ // Because, otherwise formatted result will be invalid as tsx.
+
- return group$b(concat$j(["<", indent$f(concat$j([softline$b, join$7(concat$j([",", line$c]), path.map(print, paramsKey))])), ifBreak$7(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$5(options, "all") ? "," : ""), softline$b, ">"]), {
- id: getTypeParametersGroupId(n)
+ const trailingComma = node.type === "TSTypeParameterInstantiation" // https://github.com/microsoft/TypeScript/issues/21984
+ ? "" : getFunctionParameters$1(node).length === 1 && isTSXFile(options) && !node[paramsKey][0].constraint && path.getParentNode().type === "ArrowFunctionExpression" ? "," : shouldPrintComma$6(options, "all") ? ifBreak$g(",") : "";
+ return group$o(["<", indent$i([softline$i, join$k([",", line$n], path.map(print, paramsKey))]), trailingComma, softline$i, ">"], {
+ id: getTypeParametersGroupId$2(node)
});
}
function printDanglingCommentsForInline(path, options) {
- const n = path.getValue();
+ const node = path.getValue();
- if (!hasDanglingComments$4(n)) {
+ if (!hasComment$8(node, CommentCheckFlags$8.Dangling)) {
return "";
}
- const hasOnlyBlockComments = n.comments.every(comment => isBlockComment$7(comment));
- const printed = printDanglingComments$6(path, options,
+ const hasOnlyBlockComments = !hasComment$8(node, CommentCheckFlags$8.Line);
+ const printed = printDanglingComments$8(path, options,
/* sameIndent */
hasOnlyBlockComments);
@@ -43573,151 +45789,242 @@ function printDanglingCommentsForInline(path, options) {
return printed;
}
- return concat$j([printed, hardline$c]);
+ return [printed, hardline$r];
+}
+
+function printTypeParameter$2(path, options, print) {
+ const node = path.getValue();
+ const parts = [];
+ const parent = path.getParentNode();
+
+ if (parent.type === "TSMappedType") {
+ parts.push("[", print("name"));
+
+ if (node.constraint) {
+ parts.push(" in ", print("constraint"));
+ }
+
+ if (parent.nameType) {
+ parts.push(" as ", path.callParent(() => print("nameType")));
+ }
+
+ parts.push("]");
+ return parts;
+ }
+
+ if (node.variance) {
+ parts.push(print("variance"));
+ }
+
+ parts.push(print("name"));
+
+ if (node.bound) {
+ parts.push(": ", print("bound"));
+ }
+
+ if (node.constraint) {
+ parts.push(" extends ", print("constraint"));
+ }
+
+ if (node.default) {
+ parts.push(" = ", print("default"));
+ }
+
+ return parts;
}
var typeParameters = {
- printTypeParameters,
- getTypeParametersGroupId
+ printTypeParameter: printTypeParameter$2,
+ printTypeParameters: printTypeParameters$2,
+ getTypeParametersGroupId: getTypeParametersGroupId$2
};
const {
- printComments: printComments$2
-} = comments;
-const {
- printString: printString$1,
- printNumber: printNumber$1
-} = util;
+ printComments: printComments$1
+} = comments$4;
const {
- builders: {
- concat: concat$k
- }
-} = document;
+ printString: printString$3,
+ printNumber: printNumber$3
+} = util$8;
const {
- isNumericLiteral: isNumericLiteral$1,
- isSimpleNumber: isSimpleNumber$1,
- isStringLiteral: isStringLiteral$2,
- isStringPropSafeToUnquote: isStringPropSafeToUnquote$1,
+ isNumericLiteral,
+ isSimpleNumber,
+ isStringLiteral,
+ isStringPropSafeToUnquote,
rawText: rawText$2
-} = utils$6;
+} = utils$5;
+const {
+ printAssignment: printAssignment$1
+} = assignment;
const needsQuoteProps = new WeakMap();
-function printPropertyKey(path, options, print) {
+function printPropertyKey$4(path, options, print) {
const node = path.getNode();
if (node.computed) {
- return concat$k(["[", path.call(print, "key"), "]"]);
+ return ["[", print("key"), "]"];
}
const parent = path.getParentNode();
const {
key
- } = node;
+ } = node; // flow has `Identifier` key, other parsers use `PrivateIdentifier` (ESTree) or `PrivateName`
- if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
- key.type === "Identifier") {
- return concat$k(["#", path.call(print, "key")]);
+ if (node.type === "ClassPrivateProperty" && key.type === "Identifier") {
+ return ["#", print("key")];
}
if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
- const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$2(prop.key) && !isStringPropSafeToUnquote$1(prop, options));
+ const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral(prop.key) && !isStringPropSafeToUnquote(prop, options));
needsQuoteProps.set(parent, objectHasStringProp);
}
- if ((key.type === "Identifier" || isNumericLiteral$1(key) && isSimpleNumber$1(printNumber$1(rawText$2(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
- String(key.value) === printNumber$1(rawText$2(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as
+ if ((key.type === "Identifier" || isNumericLiteral(key) && isSimpleNumber(printNumber$3(rawText$2(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
+ String(key.value) === printNumber$3(rawText$2(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as
// mentioned in `isStringPropSafeToUnquote`).
!(options.parser === "typescript" || options.parser === "babel-ts")) && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
// a -> "a"
// 1 -> "1"
// 1.5 -> "1.5"
- const prop = printString$1(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options);
- return path.call(keyPath => printComments$2(keyPath, () => prop, options), "key");
+ const prop = printString$3(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options);
+ return path.call(keyPath => printComments$1(keyPath, prop, options), "key");
}
- if (isStringPropSafeToUnquote$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
+ if (isStringPropSafeToUnquote(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
// 'a' -> a
// '1' -> 1
// '1.5' -> 1.5
- return path.call(keyPath => printComments$2(keyPath, () => /^\d/.test(key.value) ? printNumber$1(key.value) : key.value, options), "key");
+ return path.call(keyPath => printComments$1(keyPath, /^\d/.test(key.value) ? printNumber$3(key.value) : key.value, options), "key");
}
- return path.call(print, "key");
+ return print("key");
}
-var property$1 = {
- printPropertyKey
+function printProperty$1(path, options, print) {
+ const node = path.getValue();
+
+ if (node.shorthand) {
+ return print("value");
+ }
+
+ return printAssignment$1(path, options, print, printPropertyKey$4(path, options, print), ":", "value");
+}
+
+var property = {
+ printProperty: printProperty$1,
+ printPropertyKey: printPropertyKey$4
};
-/** @type {import("assert")} */
+/** @typedef {import("../../document/doc-builders").Doc} Doc */
+const assert$2 = require$$0__default$3["default"];
const {
- printDanglingComments: printDanglingComments$7
-} = comments;
+ printDanglingComments: printDanglingComments$7,
+ printCommentsSeparately
+} = comments$4;
+const getLast$b = getLast_1;
const {
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3
-} = util;
+ getNextNonSpaceNonCommentCharacterIndex
+} = util$8;
const {
builders: {
- concat: concat$l,
- line: line$d,
- softline: softline$c,
- group: group$c,
- indent: indent$g,
- ifBreak: ifBreak$8,
- hardline: hardline$d
+ line: line$m,
+ softline: softline$h,
+ group: group$n,
+ indent: indent$h,
+ ifBreak: ifBreak$f,
+ hardline: hardline$q,
+ join: join$j,
+ indentIfBreak: indentIfBreak$1
+ },
+ utils: {
+ removeLines: removeLines$1,
+ willBreak
}
-} = document;
+} = require$$7$3;
const {
- getFunctionParameters: getFunctionParameters$4,
- hasDanglingComments: hasDanglingComments$5,
- hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
- isFlowAnnotationComment: isFlowAnnotationComment$2,
- isJSXNode: isJSXNode$4,
- isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
- shouldPrintComma: shouldPrintComma$6,
- startsWithNoLookaheadToken: startsWithNoLookaheadToken$2,
- returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1,
- isBinaryish: isBinaryish$3,
- isLineComment: isLineComment$1
-} = utils$6;
+ ArgExpansionBailout
+} = errors;
const {
- locEnd: locEnd$8
-} = loc;
+ getFunctionParameters,
+ hasLeadingOwnLineComment,
+ isFlowAnnotationComment,
+ isJsxNode: isJsxNode$2,
+ isTemplateOnItsOwnLine,
+ shouldPrintComma: shouldPrintComma$5,
+ startsWithNoLookaheadToken,
+ isBinaryish,
+ isLineComment: isLineComment$2,
+ hasComment: hasComment$7,
+ getComments: getComments$2,
+ CommentCheckFlags: CommentCheckFlags$7,
+ isCallLikeExpression,
+ isCallExpression: isCallExpression$3,
+ getCallArguments,
+ hasNakedLeftSide: hasNakedLeftSide$1,
+ getLeftSide
+} = utils$5;
+const {
+ locEnd: locEnd$l
+} = loc$6;
const {
- printFunctionParameters: printFunctionParameters$1
+ printFunctionParameters: printFunctionParameters$1,
+ shouldGroupFunctionParameters: shouldGroupFunctionParameters$1
} = functionParameters;
const {
- printPropertyKey: printPropertyKey$1
-} = property$1;
+ printPropertyKey: printPropertyKey$3
+} = property;
const {
- printFunctionTypeParameters: printFunctionTypeParameters$2
-} = misc;
+ printFunctionTypeParameters
+} = misc$1;
-function printFunctionDeclaration(path, print, options, expandArg) {
- const n = path.getValue();
- const parts = [];
+function printFunction$2(path, print, options, args) {
+ const node = path.getValue();
+ let expandArg = false;
+
+ if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression") && args && args.expandLastArg) {
+ const parent = path.getParentNode();
+
+ if (isCallExpression$3(parent) && getCallArguments(parent).length > 1) {
+ expandArg = true;
+ }
+ }
+
+ const parts = []; // For TypeScript the TSDeclareFunction node shares the AST
+ // structure with FunctionDeclaration
+
+ if (node.type === "TSDeclareFunction" && node.declare) {
+ parts.push("declare ");
+ }
- if (n.async) {
+ if (node.async) {
parts.push("async ");
}
- if (n.generator) {
+ if (node.generator) {
parts.push("function* ");
} else {
parts.push("function ");
}
- if (n.id) {
- parts.push(path.call(print, "id"));
+ if (node.id) {
+ parts.push(print("id"));
+ }
+
+ const parametersDoc = printFunctionParameters$1(path, print, options, expandArg);
+ const returnTypeDoc = printReturnType(path, print, options);
+ const shouldGroupParameters = shouldGroupFunctionParameters$1(node, returnTypeDoc);
+ parts.push(printFunctionTypeParameters(path, options, print), group$n([shouldGroupParameters ? group$n(parametersDoc) : parametersDoc, returnTypeDoc]), node.body ? " " : "", print("body"));
+
+ if (options.semi && (node.declare || !node.body)) {
+ parts.push(";");
}
- parts.push(printFunctionTypeParameters$2(path, options, print), group$c(concat$l([printFunctionParameters$1(path, print, options, expandArg), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
- return concat$l(parts);
+ return parts;
}
-function printMethod(path, options, print) {
+function printMethod$2(path, options, print) {
const node = path.getNode();
const {
kind
@@ -43730,7 +46037,7 @@ function printMethod(path, options, print) {
parts.push("async ");
}
} else {
- assert__default['default'].ok(kind === "get" || kind === "set");
+ assert$2.ok(kind === "get" || kind === "set");
parts.push(kind, " ");
} // A `getter`/`setter` can't be a generator, but it's recoverable
@@ -43739,86 +46046,174 @@ function printMethod(path, options, print) {
parts.push("*");
}
- parts.push(printPropertyKey$1(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
- return concat$l(parts);
+ parts.push(printPropertyKey$3(path, options, print), node.optional || node.key.optional ? "?" : "");
+
+ if (node === value) {
+ parts.push(printMethodInternal$1(path, options, print));
+ } else if (value.type === "FunctionExpression") {
+ parts.push(path.call(path => printMethodInternal$1(path, options, print), "value"));
+ } else {
+ parts.push(print("value"));
+ }
+
+ return parts;
}
-function printMethodInternal(path, options, print) {
- const parts = [printFunctionTypeParameters$2(path, options, print), group$c(concat$l([printFunctionParameters$1(path, print, options), printReturnType(path, print, options)]))];
+function printMethodInternal$1(path, options, print) {
+ const node = path.getNode();
+ const parametersDoc = printFunctionParameters$1(path, print, options);
+ const returnTypeDoc = printReturnType(path, print, options);
+ const shouldGroupParameters = shouldGroupFunctionParameters$1(node, returnTypeDoc);
+ const parts = [printFunctionTypeParameters(path, options, print), group$n([shouldGroupParameters ? group$n(parametersDoc) : parametersDoc, returnTypeDoc])];
- if (path.getNode().body) {
- parts.push(" ", path.call(print, "body"));
+ if (node.body) {
+ parts.push(" ", print("body"));
} else {
parts.push(options.semi ? ";" : "");
}
- return concat$l(parts);
+ return parts;
}
-function printArrowFunctionExpression(path, options, print, args) {
- const n = path.getValue();
+function printArrowFunctionSignature(path, options, print, args) {
+ const node = path.getValue();
const parts = [];
- if (n.async) {
+ if (node.async) {
parts.push("async ");
}
- if (shouldPrintParamsWithoutParens(path, options)) {
- parts.push(path.call(print, "params", 0));
- } else {
- parts.push(group$c(concat$l([printFunctionParameters$1(path, print, options,
- /* expandLast */
- args && (args.expandLastArg || args.expandFirstArg),
- /* printTypeParams */
- true), printReturnType(path, print, options)])));
- }
+ if (shouldPrintParamsWithoutParens$1(path, options)) {
+ parts.push(print(["params", 0]));
+ } else {
+ const expandArg = args && (args.expandLastArg || args.expandFirstArg);
+ let returnTypeDoc = printReturnType(path, print, options);
+
+ if (expandArg) {
+ if (willBreak(returnTypeDoc)) {
+ throw new ArgExpansionBailout();
+ }
+
+ returnTypeDoc = group$n(removeLines$1(returnTypeDoc));
+ }
+
+ parts.push(group$n([printFunctionParameters$1(path, print, options, expandArg,
+ /* printTypeParams */
+ true), returnTypeDoc]));
+ }
+
+ const dangling = printDanglingComments$7(path, options,
+ /* sameIndent */
+ true, comment => {
+ const nextCharacter = getNextNonSpaceNonCommentCharacterIndex(options.originalText, comment, locEnd$l);
+ return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
+ });
+
+ if (dangling) {
+ parts.push(" ", dangling);
+ }
+
+ return parts;
+}
+
+function printArrowChain(path, args, signatures, shouldBreak, bodyDoc, tailNode) {
+ const name = path.getName();
+ const parent = path.getParentNode();
+ const isCallee = isCallLikeExpression(parent) && name === "callee";
+ const isAssignmentRhs = Boolean(args && args.assignmentLayout);
+ const shouldPutBodyOnSeparateLine = tailNode.body.type !== "BlockStatement" && tailNode.body.type !== "ObjectExpression" && tailNode.body.type !== "SequenceExpression";
+ const shouldBreakBeforeChain = isCallee && shouldPutBodyOnSeparateLine || args && args.assignmentLayout === "chain-tail-arrow-chain";
+ const groupId = Symbol("arrow-chain"); // We handle sequence expressions as the body of arrows specially,
+ // so that the required parentheses end up on their own lines.
+
+ if (tailNode.body.type === "SequenceExpression") {
+ bodyDoc = group$n(["(", indent$h([softline$h, bodyDoc]), softline$h, ")"]);
+ }
+
+ return group$n([group$n(indent$h([isCallee || isAssignmentRhs ? softline$h : "", group$n(join$j([" =>", line$m], signatures), {
+ shouldBreak
+ })]), {
+ id: groupId,
+ shouldBreak: shouldBreakBeforeChain
+ }), " =>", indentIfBreak$1(shouldPutBodyOnSeparateLine ? indent$h([line$m, bodyDoc]) : [" ", bodyDoc], {
+ groupId
+ }), isCallee ? ifBreak$f(softline$h, "", {
+ groupId
+ }) : ""]);
+}
+
+function printArrowFunction$1(path, options, print, args) {
+ let node = path.getValue();
+ /** @type {Doc[]} */
+
+ const signatures = [];
+ const body = [];
+ let chainShouldBreak = false;
+
+ (function rec() {
+ const doc = printArrowFunctionSignature(path, options, print, args);
+
+ if (signatures.length === 0) {
+ signatures.push(doc);
+ } else {
+ const {
+ leading,
+ trailing
+ } = printCommentsSeparately(path, options);
+ signatures.push([leading, doc]);
+ body.unshift(trailing);
+ }
- const dangling = printDanglingComments$7(path, options,
- /* sameIndent */
- true, comment => {
- const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$3(options.originalText, comment, locEnd$8);
- return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
- });
+ chainShouldBreak = chainShouldBreak || // Always break the chain if:
+ node.returnType && getFunctionParameters(node).length > 0 || node.typeParameters || getFunctionParameters(node).some(param => param.type !== "Identifier");
- if (dangling) {
- parts.push(" ", dangling);
+ if (node.body.type !== "ArrowFunctionExpression" || args && args.expandLastArg) {
+ body.unshift(print("body", args));
+ } else {
+ node = node.body;
+ path.call(rec, "body");
+ }
+ })();
+
+ if (signatures.length > 1) {
+ return printArrowChain(path, args, signatures, chainShouldBreak, body, node);
}
- parts.push(" =>");
- const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line
+ const parts = signatures;
+ parts.push(" =>"); // We want to always keep these types of nodes on the same line
// as the arrow.
- if (!hasLeadingOwnLineComment$1(options.originalText, n.body) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$4(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
- return group$c(concat$l([concat$l(parts), " ", body]));
+ if (!hasLeadingOwnLineComment(options.originalText, node.body) && (node.body.type === "ArrayExpression" || node.body.type === "ObjectExpression" || node.body.type === "BlockStatement" || isJsxNode$2(node.body) || isTemplateOnItsOwnLine(node.body, options.originalText) || node.body.type === "ArrowFunctionExpression" || node.body.type === "DoExpression")) {
+ return group$n([...parts, " ", body]);
} // We handle sequence expressions as the body of arrows specially,
// so that the required parentheses end up on their own lines.
- if (n.body.type === "SequenceExpression") {
- return group$c(concat$l([concat$l(parts), group$c(concat$l([" (", indent$g(concat$l([softline$c, body])), softline$c, ")"]))]));
+ if (node.body.type === "SequenceExpression") {
+ return group$n([...parts, group$n([" (", indent$h([softline$h, body]), softline$h, ")"])]);
} // if the arrow function is expanded as last argument, we are adding a
// level of indentation and need to add a softline to align the closing )
// with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
// we should align the expression's closing } with the line with the opening {.
- const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
- const printTrailingComma = args && args.expandLastArg && shouldPrintComma$6(options, "all"); // In order to avoid confusion between
+ const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !hasComment$7(node);
+ const printTrailingComma = args && args.expandLastArg && shouldPrintComma$5(options, "all"); // In order to avoid confusion between
// a => a ? a : a
// a <= a ? a : a
- const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$2(n.body,
+ const shouldAddParens = node.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken(node.body,
/* forbidFunctionAndClass */
false);
- return group$c(concat$l([concat$l(parts), group$c(concat$l([indent$g(concat$l([line$d, shouldAddParens ? ifBreak$8("", "(") : "", body, shouldAddParens ? ifBreak$8("", ")") : ""])), shouldAddSoftLine ? concat$l([ifBreak$8(printTrailingComma ? "," : ""), softline$c]) : ""]))]));
+ return group$n([...parts, group$n([indent$h([line$m, shouldAddParens ? ifBreak$f("", "(") : "", body, shouldAddParens ? ifBreak$f("", ")") : ""]), shouldAddSoftLine ? [ifBreak$f(printTrailingComma ? "," : ""), softline$h] : ""])]);
}
function canPrintParamsWithoutParens(node) {
- const parameters = getFunctionParameters$4(node);
- return parameters.length === 1 && !node.typeParameters && !hasDanglingComments$5(node) && parameters[0].type === "Identifier" && !parameters[0].typeAnnotation && !parameters[0].comments && !parameters[0].optional && !node.predicate && !node.returnType;
+ const parameters = getFunctionParameters(node);
+ return parameters.length === 1 && !node.typeParameters && !hasComment$7(node, CommentCheckFlags$7.Dangling) && parameters[0].type === "Identifier" && !parameters[0].typeAnnotation && !hasComment$7(parameters[0]) && !parameters[0].optional && !node.predicate && !node.returnType;
}
-function shouldPrintParamsWithoutParens(path, options) {
+function shouldPrintParamsWithoutParens$1(path, options) {
if (options.arrowParens === "always") {
return false;
}
@@ -43833,54 +46228,57 @@ function shouldPrintParamsWithoutParens(path, options) {
return false;
}
+/** @returns {Doc} */
+
function printReturnType(path, print, options) {
- const n = path.getValue();
- const returnType = path.call(print, "returnType");
+ const node = path.getValue();
+ const returnType = print("returnType");
- if (n.returnType && isFlowAnnotationComment$2(options.originalText, n.returnType)) {
- return concat$l([" /*: ", returnType, " */"]);
+ if (node.returnType && isFlowAnnotationComment(options.originalText, node.returnType)) {
+ return [" /*: ", returnType, " */"];
}
const parts = [returnType]; // prepend colon to TypeScript type annotation
- if (n.returnType && n.returnType.typeAnnotation) {
+ if (node.returnType && node.returnType.typeAnnotation) {
parts.unshift(": ");
}
- if (n.predicate) {
+ if (node.predicate) {
// The return type will already add the colon, but otherwise we
// need to do it ourselves
- parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
+ parts.push(node.returnType ? " " : ": ", print("predicate"));
}
- return concat$l(parts);
+ return parts;
} // `ReturnStatement` and `ThrowStatement`
-function printReturnAndThrowArgument(path, options, print) {
+function printReturnOrThrowArgument(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
const parts = [];
if (node.argument) {
- if (returnArgumentHasLeadingComment$1(options, node.argument)) {
- parts.push(concat$l([" (", indent$g(concat$l([hardline$d, path.call(print, "argument")])), hardline$d, ")"]));
- } else if (isBinaryish$3(node.argument) || node.argument.type === "SequenceExpression") {
- parts.push(group$c(concat$l([ifBreak$8(" (", " "), indent$g(concat$l([softline$c, path.call(print, "argument")])), softline$c, ifBreak$8(")")])));
+ if (returnArgumentHasLeadingComment(options, node.argument)) {
+ parts.push([" (", indent$h([hardline$q, print("argument")]), hardline$q, ")"]);
+ } else if (isBinaryish(node.argument) || node.argument.type === "SequenceExpression") {
+ parts.push(group$n([ifBreak$f(" (", " "), indent$h([softline$h, print("argument")]), softline$h, ifBreak$f(")")]));
} else {
- parts.push(" ", path.call(print, "argument"));
+ parts.push(" ", print("argument"));
}
}
- const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
- const isLastCommentLine = lastComment && isLineComment$1(lastComment);
+ const comments = getComments$2(node);
+ const lastComment = getLast$b(comments);
+ const isLastCommentLine = lastComment && isLineComment$2(lastComment);
if (isLastCommentLine) {
parts.push(semi);
}
- if (hasDanglingComments$5(node)) {
+ if (hasComment$7(node, CommentCheckFlags$7.Dangling)) {
parts.push(" ", printDanglingComments$7(path, options,
/* sameIndent */
true));
@@ -43890,37 +46288,145 @@ function printReturnAndThrowArgument(path, options, print) {
parts.push(semi);
}
- return concat$l(parts);
+ return parts;
+}
+
+function printReturnStatement$1(path, options, print) {
+ return ["return", printReturnOrThrowArgument(path, options, print)];
+}
+
+function printThrowStatement$1(path, options, print) {
+ return ["throw", printReturnOrThrowArgument(path, options, print)];
+} // 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)) {
+ return true;
+ }
+
+ if (hasNakedLeftSide$1(argument)) {
+ let leftMost = argument;
+ let newLeftMost;
+
+ while (newLeftMost = getLeftSide(leftMost)) {
+ leftMost = newLeftMost;
+
+ if (hasLeadingOwnLineComment(options.originalText, leftMost)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
}
var _function = {
- printFunctionDeclaration,
- printArrowFunctionExpression,
- printMethod,
- printReturnAndThrowArgument,
- shouldPrintParamsWithoutParens
+ printFunction: printFunction$2,
+ printArrowFunction: printArrowFunction$1,
+ printMethod: printMethod$2,
+ printReturnStatement: printReturnStatement$1,
+ printThrowStatement: printThrowStatement$1,
+ printMethodInternal: printMethodInternal$1,
+ shouldPrintParamsWithoutParens: shouldPrintParamsWithoutParens$1
};
const {
- printComments: printComments$3,
- printDanglingComments: printDanglingComments$8
-} = comments;
+ isNonEmptyArray: isNonEmptyArray$c,
+ hasNewline: hasNewline$4
+} = util$8;
const {
builders: {
- concat: concat$m,
- join: join$8,
- line: line$e,
- hardline: hardline$e,
- softline: softline$d,
- group: group$d,
- indent: indent$h,
- ifBreak: ifBreak$9
+ line: line$l,
+ hardline: hardline$p,
+ join: join$i,
+ breakParent: breakParent$7,
+ group: group$m
}
-} = document;
+} = require$$7$3;
const {
- hasTrailingComment: hasTrailingComment$2,
- hasTrailingLineComment: hasTrailingLineComment$1
-} = utils$6;
+ locStart: locStart$m,
+ locEnd: locEnd$k
+} = loc$6;
+const {
+ getParentExportDeclaration: getParentExportDeclaration$1
+} = utils$5;
+
+function printClassMemberDecorators$1(path, options, print) {
+ const node = path.getValue();
+ return group$m([join$i(line$l, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators(node, options) ? hardline$p : line$l]);
+}
+
+function printDecoratorsBeforeExport$1(path, options, print) {
+ // Export declarations are responsible for printing any decorators
+ // that logically apply to node.declaration.
+ return [join$i(hardline$p, path.map(print, "declaration", "decorators")), hardline$p];
+}
+
+function printDecorators$1(path, options, print) {
+ const node = path.getValue();
+ const {
+ decorators
+ } = node;
+
+ if (!isNonEmptyArray$c(decorators) || // If the parent node is an export declaration and the decorator
+ // was written before the export, the export will be responsible
+ // for printing the decorators.
+ hasDecoratorsBeforeExport$1(path.getParentNode())) {
+ return;
+ }
+
+ const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators(node, options);
+ return [getParentExportDeclaration$1(path) ? hardline$p : shouldBreak ? breakParent$7 : "", join$i(line$l, path.map(print, "decorators")), line$l];
+}
+
+function hasNewlineBetweenOrAfterDecorators(node, options) {
+ return node.decorators.some(decorator => hasNewline$4(options.originalText, locEnd$k(decorator)));
+}
+
+function hasDecoratorsBeforeExport$1(node) {
+ if (node.type !== "ExportDefaultDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "DeclareExportDeclaration") {
+ return false;
+ }
+
+ const decorators = node.declaration && node.declaration.decorators;
+ return isNonEmptyArray$c(decorators) && locStart$m(node, {
+ ignoreDecorators: true
+ }) > locStart$m(decorators[0]);
+}
+
+var decorators = {
+ printDecorators: printDecorators$1,
+ printClassMemberDecorators: printClassMemberDecorators$1,
+ printDecoratorsBeforeExport: printDecoratorsBeforeExport$1,
+ hasDecoratorsBeforeExport: hasDecoratorsBeforeExport$1
+};
+
+const {
+ isNonEmptyArray: isNonEmptyArray$b,
+ createGroupIdMapper
+} = util$8;
+const {
+ printComments,
+ printDanglingComments: printDanglingComments$6
+} = comments$4;
+const {
+ builders: {
+ join: join$h,
+ line: line$k,
+ hardline: hardline$o,
+ softline: softline$g,
+ group: group$l,
+ indent: indent$g,
+ ifBreak: ifBreak$e
+ }
+} = require$$7$3;
+const {
+ hasComment: hasComment$6,
+ CommentCheckFlags: CommentCheckFlags$6
+} = utils$5;
const {
getTypeParametersGroupId: getTypeParametersGroupId$1
} = typeParameters;
@@ -43928,37 +46434,51 @@ const {
printMethod: printMethod$1
} = _function;
const {
- printDecorators: printDecorators$1
-} = misc;
+ printOptionalToken: printOptionalToken$4,
+ printTypeAnnotation: printTypeAnnotation$3
+} = misc$1;
+const {
+ printPropertyKey: printPropertyKey$2
+} = property;
+const {
+ printAssignment
+} = assignment;
+const {
+ printClassMemberDecorators
+} = decorators;
-function printClass(path, options, print) {
- const n = path.getValue();
+function printClass$2(path, options, print) {
+ const node = path.getValue();
const parts = [];
- if (n.abstract) {
+ if (node.declare) {
+ parts.push("declare ");
+ }
+
+ if (node.abstract) {
parts.push("abstract ");
}
parts.push("class"); // Keep old behaviour of extends in same line
// If there is only on extends and there are not comments
- const groupMode = n.id && hasTrailingComment$2(n.id) || n.superClass && n.superClass.comments && n.superClass.comments.length !== 0 || n.extends && n.extends.length !== 0 || // DeclareClass
- n.mixins && n.mixins.length !== 0 || n.implements && n.implements.length !== 0;
+ const groupMode = node.id && hasComment$6(node.id, CommentCheckFlags$6.Trailing) || node.superClass && hasComment$6(node.superClass) || isNonEmptyArray$b(node.extends) || // DeclareClass
+ isNonEmptyArray$b(node.mixins) || isNonEmptyArray$b(node.implements);
const partsGroup = [];
const extendsParts = [];
- if (n.id) {
- partsGroup.push(" ", path.call(print, "id"));
+ if (node.id) {
+ partsGroup.push(" ", print("id"));
}
- partsGroup.push(path.call(print, "typeParameters"));
+ partsGroup.push(print("typeParameters"));
- if (n.superClass) {
- const printed = concat$m(["extends ", printSuperClass(path, options, print), path.call(print, "superTypeParameters")]);
- const printedWithComments = path.call(superClass => printComments$3(superClass, () => printed, options), "superClass");
+ if (node.superClass) {
+ const printed = ["extends ", printSuperClass(path, options, print), print("superTypeParameters")];
+ const printedWithComments = path.call(superClass => printComments(superClass, printed, options), "superClass");
if (groupMode) {
- extendsParts.push(line$e, group$d(printedWithComments));
+ extendsParts.push(line$k, group$l(printedWithComments));
} else {
extendsParts.push(" ", printedWithComments);
}
@@ -43966,3215 +46486,3100 @@ function printClass(path, options, print) {
extendsParts.push(printList(path, options, print, "extends"));
}
- extendsParts.push(printList(path, options, print, "mixins"));
- extendsParts.push(printList(path, options, print, "implements"));
+ extendsParts.push(printList(path, options, print, "mixins"), printList(path, options, print, "implements"));
if (groupMode) {
- const printedExtends = concat$m(extendsParts);
+ let printedPartsGroup;
- if (shouldIndentOnlyHeritageClauses(n)) {
- parts.push(group$d(concat$m(partsGroup.concat(ifBreak$9(indent$h(printedExtends), printedExtends)))));
+ if (shouldIndentOnlyHeritageClauses(node)) {
+ printedPartsGroup = [...partsGroup, indent$g(extendsParts)];
} else {
- parts.push(group$d(indent$h(concat$m(partsGroup.concat(printedExtends)))));
+ printedPartsGroup = indent$g([...partsGroup, extendsParts]);
}
+
+ parts.push(group$l(printedPartsGroup, {
+ id: getHeritageGroupId(node)
+ }));
} else {
parts.push(...partsGroup, ...extendsParts);
}
- parts.push(" ", path.call(print, "body"));
- return concat$m(parts);
+ parts.push(" ", print("body"));
+ return parts;
+}
+
+const getHeritageGroupId = createGroupIdMapper("heritageGroup");
+
+function printHardlineAfterHeritage$2(node) {
+ return ifBreak$e(hardline$o, "", {
+ groupId: getHeritageGroupId(node)
+ });
}
function hasMultipleHeritage(node) {
- return ["superClass", "extends", "mixins", "implements"].filter(key => !!node[key]).length > 1;
+ return ["superClass", "extends", "mixins", "implements"].filter(key => Boolean(node[key])).length > 1;
}
function shouldIndentOnlyHeritageClauses(node) {
- return node.typeParameters && !hasTrailingLineComment$1(node.typeParameters) && !hasMultipleHeritage(node);
+ return node.typeParameters && !hasComment$6(node.typeParameters, CommentCheckFlags$6.Trailing | CommentCheckFlags$6.Line) && !hasMultipleHeritage(node);
}
function printList(path, options, print, listName) {
- const n = path.getValue();
+ const node = path.getValue();
- if (!n[listName] || n[listName].length === 0) {
+ if (!isNonEmptyArray$b(node[listName])) {
return "";
}
- const printedLeadingComments = printDanglingComments$8(path, options,
+ const printedLeadingComments = printDanglingComments$6(path, options,
/* sameIndent */
true, ({
marker
}) => marker === listName);
- return concat$m([shouldIndentOnlyHeritageClauses(n) ? ifBreak$9(" ", line$e, {
- groupId: getTypeParametersGroupId$1(n.typeParameters)
- }) : line$e, printedLeadingComments, printedLeadingComments && hardline$e, listName, group$d(indent$h(concat$m([line$e, join$8(concat$m([",", line$e]), path.map(print, listName))])))]);
+ return [shouldIndentOnlyHeritageClauses(node) ? ifBreak$e(" ", line$k, {
+ groupId: getTypeParametersGroupId$1(node.typeParameters)
+ }) : line$k, printedLeadingComments, printedLeadingComments && hardline$o, listName, group$l(indent$g([line$k, join$h([",", line$k], path.map(print, listName))]))];
}
function printSuperClass(path, options, print) {
- const printed = path.call(print, "superClass");
+ const printed = print("superClass");
const parent = path.getParentNode();
if (parent.type === "AssignmentExpression") {
- return group$d(ifBreak$9(concat$m(["(", indent$h(concat$m([softline$d, printed])), softline$d, ")"]), printed));
+ return group$l(ifBreak$e(["(", indent$g([softline$g, printed]), softline$g, ")"], printed));
}
return printed;
}
-function printClassMethod(path, options, print) {
- const n = path.getValue();
+function printClassMethod$2(path, options, print) {
+ const node = path.getValue();
const parts = [];
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators$1(path, options, print));
+ if (isNonEmptyArray$b(node.decorators)) {
+ parts.push(printClassMemberDecorators(path, options, print));
+ }
+
+ if (node.accessibility) {
+ parts.push(node.accessibility + " ");
+ } // "readonly" and "declare" are supported by only "babel-ts"
+ // https://github.com/prettier/prettier/issues/9760
+
+
+ if (node.readonly) {
+ parts.push("readonly ");
}
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
+ if (node.declare) {
+ parts.push("declare ");
}
- if (n.static) {
+ if (node.static) {
parts.push("static ");
}
- if (n.type === "TSAbstractMethodDefinition" || n.abstract) {
+ if (node.type === "TSAbstractMethodDefinition" || node.abstract) {
parts.push("abstract ");
}
+ if (node.override) {
+ parts.push("override ");
+ }
+
parts.push(printMethod$1(path, options, print));
- return concat$m(parts);
+ return parts;
}
-var _class = {
- printClass,
- printClassMethod
-};
-
-const {
- getLast: getLast$6,
- getPenultimate: getPenultimate$1,
- isNextLineEmpty: isNextLineEmpty$5
-} = util;
-const {
- getFunctionParameters: getFunctionParameters$5,
- iterateFunctionParametersPath: iterateFunctionParametersPath$2,
- hasLeadingComment: hasLeadingComment$3,
- hasTrailingComment: hasTrailingComment$3,
- isFunctionCompositionArgs: isFunctionCompositionArgs$1,
- isJSXNode: isJSXNode$5,
- isLongCurriedCallExpression: isLongCurriedCallExpression$1,
- shouldPrintComma: shouldPrintComma$7,
- getCallArguments: getCallArguments$1,
- iterateCallArgumentsPath: iterateCallArgumentsPath$1
-} = utils$6;
-const {
- locEnd: locEnd$9
-} = loc;
-const {
- builders: {
- concat: concat$n,
- line: line$f,
- hardline: hardline$f,
- softline: softline$e,
- group: group$e,
- indent: indent$i,
- conditionalGroup: conditionalGroup$2,
- ifBreak: ifBreak$a,
- breakParent: breakParent$3
- },
- utils: {
- willBreak: willBreak$2
- }
-} = document;
-
-function printCallArguments(path, options, print) {
+function printClassProperty$2(path, options, print) {
const node = path.getValue();
- const isDynamicImport = node.type === "ImportExpression";
- const args = getCallArguments$1(node);
-
- if (args.length === 0) {
- return concat$n(["(", comments.printDanglingComments(path, options,
- /* sameIndent */
- true), ")"]);
- } // useEffect(() => { ... }, [foo, bar, baz])
-
-
- if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && getFunctionParameters$5(args[0]).length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.some(arg => arg.comments)) {
- return concat$n(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
- } // func(
- // ({
- // a,
- //
- // b
- // }) => {}
- // );
-
-
- function shouldBreakForArrowFunctionInArguments(arg, argPath) {
- if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || getFunctionParameters$5(arg).length === 0) {
- return false;
- }
+ const parts = [];
+ const semi = options.semi ? ";" : "";
- let shouldBreak = false;
- iterateFunctionParametersPath$2(argPath, parameterPath => {
- shouldBreak = shouldBreak || willBreak$2(concat$n([print(parameterPath)]));
- });
- return shouldBreak;
+ if (isNonEmptyArray$b(node.decorators)) {
+ parts.push(printClassMemberDecorators(path, options, print));
}
- let anyArgEmptyLine = false;
- let shouldBreakForArrowFunction = false;
- let hasEmptyLineFollowingFirstArg = false;
- const lastArgIndex = args.length - 1;
- const printedArguments = [];
- iterateCallArgumentsPath$1(path, (argPath, index) => {
- const arg = argPath.getNode();
- const parts = [print(argPath)];
-
- if (index === lastArgIndex) ; else if (isNextLineEmpty$5(options.originalText, arg, locEnd$9)) {
- if (index === 0) {
- hasEmptyLineFollowingFirstArg = true;
- }
-
- anyArgEmptyLine = true;
- parts.push(",", hardline$f, hardline$f);
- } else {
- parts.push(",", line$f);
- }
-
- shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
- printedArguments.push(concat$n(parts));
- });
- const maybeTrailingComma = // Dynamic imports cannot have trailing commas
- !(isDynamicImport || node.callee && node.callee.type === "Import") && shouldPrintComma$7(options, "all") ? "," : "";
-
- function allArgsBrokenOut() {
- return group$e(concat$n(["(", indent$i(concat$n([line$f, concat$n(printedArguments)])), maybeTrailingComma, line$f, ")"]), {
- shouldBreak: true
- });
+ if (node.accessibility) {
+ parts.push(node.accessibility + " ");
}
- if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
- return allArgsBrokenOut();
+ if (node.declare) {
+ parts.push("declare ");
}
- const shouldGroupFirst = shouldGroupFirstArg(args);
- const shouldGroupLast = shouldGroupLastArg(args);
-
- if (shouldGroupFirst || shouldGroupLast) {
- const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$2) : printedArguments.slice(0, -1).some(willBreak$2)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
-
- let printedExpanded = [];
- iterateCallArgumentsPath$1(path, (argPath, i) => {
- if (shouldGroupFirst && i === 0) {
- printedExpanded = [concat$n([argPath.call(p => print(p, {
- expandFirstArg: true
- })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$f : line$f, hasEmptyLineFollowingFirstArg ? hardline$f : ""])].concat(printedArguments.slice(1));
- }
-
- if (shouldGroupLast && i === args.length - 1) {
- printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
- expandLastArg: true
- })));
- }
- });
- const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$2);
- const simpleConcat = concat$n(["(", concat$n(printedExpanded), ")"]);
- return concat$n([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$2([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$a(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$n(["(", group$e(printedExpanded[0], {
- shouldBreak: true
- }), concat$n(printedExpanded.slice(1)), ")"]) : concat$n(["(", concat$n(printedArguments.slice(0, -1)), group$e(getLast$6(printedExpanded), {
- shouldBreak: true
- }), ")"]), allArgsBrokenOut()], {
- shouldBreak
- })]);
+ if (node.static) {
+ parts.push("static ");
}
- const contents = concat$n(["(", indent$i(concat$n([softline$e, concat$n(printedArguments)])), ifBreak$a(maybeTrailingComma), softline$e, ")"]);
-
- if (isLongCurriedCallExpression$1(path)) {
- // By not wrapping the arguments in a group, the printer prioritizes
- // breaking up these arguments rather than the args of the parent call.
- return contents;
+ if (node.type === "TSAbstractPropertyDefinition" || node.abstract) {
+ parts.push("abstract ");
}
- return group$e(contents, {
- shouldBreak: printedArguments.some(willBreak$2) || anyArgEmptyLine
- });
-}
-
-function couldGroupArg(arg) {
- return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords
- // https://github.com/prettier/prettier/issues/4070
- // export class Thing implements OtherThing {
- // do: (type: Type) => Provider
= memoize(
- // (type: ObjectType): Provider => {}
- // );
- // }
- // https://github.com/prettier/prettier/issues/6099
- // app.get("/", (req, res): void => {
- // res.send("Hello World!");
- // });
- !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$5(arg.body));
-}
+ if (node.override) {
+ parts.push("override ");
+ }
-function shouldGroupLastArg(args) {
- const lastArg = getLast$6(args);
- const penultimateArg = getPenultimate$1(args);
- return !hasLeadingComment$3(lastArg) && !hasTrailingComment$3(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
- // disable last element expansion.
- !penultimateArg || penultimateArg.type !== lastArg.type);
-}
+ if (node.readonly) {
+ parts.push("readonly ");
+ }
-function shouldGroupFirstArg(args) {
- if (args.length !== 2) {
- return false;
+ if (node.variance) {
+ parts.push(print("variance"));
}
- const [firstArg, secondArg] = args;
- return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
+ parts.push(printPropertyKey$2(path, options, print), printOptionalToken$4(path), printTypeAnnotation$3(path, options, print));
+ return [printAssignment(path, options, print, parts, " =", "value"), semi];
}
-var callArguments = printCallArguments;
+var _class = {
+ printClass: printClass$2,
+ printClassMethod: printClassMethod$2,
+ printClassProperty: printClassProperty$2,
+ printHardlineAfterHeritage: printHardlineAfterHeritage$2
+};
+const {
+ isNonEmptyArray: isNonEmptyArray$a
+} = util$8;
const {
builders: {
- concat: concat$o,
- softline: softline$f,
- group: group$f,
- indent: indent$j
+ join: join$g,
+ line: line$j,
+ group: group$k,
+ indent: indent$f,
+ ifBreak: ifBreak$d
}
-} = document;
+} = require$$7$3;
const {
- isNumericLiteral: isNumericLiteral$2
-} = utils$6;
+ hasComment: hasComment$5,
+ identity,
+ CommentCheckFlags: CommentCheckFlags$5
+} = utils$5;
const {
- printOptionalToken: printOptionalToken$3
-} = misc;
+ getTypeParametersGroupId
+} = typeParameters;
+const {
+ printTypeScriptModifiers: printTypeScriptModifiers$1
+} = misc$1;
-function printMemberExpression(path, options, print) {
- const n = path.getValue();
- const parent = path.getParentNode();
- let firstNonMemberParent;
- let i = 0;
+function printInterface$2(path, options, print) {
+ const node = path.getValue();
+ const parts = [];
- do {
- firstNonMemberParent = path.getParentNode(i);
- i++;
- } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
+ if (node.declare) {
+ parts.push("declare ");
+ }
- const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression";
- return concat$o([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$f(indent$j(concat$o([softline$f, printMemberLookup(path, options, print)])))]);
-}
+ if (node.type === "TSInterfaceDeclaration") {
+ parts.push(node.abstract ? "abstract " : "", printTypeScriptModifiers$1(path, options, print));
+ }
-function printMemberLookup(path, options, print) {
- const property = path.call(print, "property");
- const n = path.getValue();
- const optional = printOptionalToken$3(path);
+ parts.push("interface");
+ const partsGroup = [];
+ const extendsParts = [];
+
+ if (node.type !== "InterfaceTypeAnnotation") {
+ partsGroup.push(" ", print("id"), print("typeParameters"));
+ }
+
+ const shouldIndentOnlyHeritageClauses = node.typeParameters && !hasComment$5(node.typeParameters, CommentCheckFlags$5.Trailing | CommentCheckFlags$5.Line);
- if (!n.computed) {
- return concat$o([optional, ".", property]);
+ if (isNonEmptyArray$a(node.extends)) {
+ extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$d(" ", line$j, {
+ groupId: getTypeParametersGroupId(node.typeParameters)
+ }) : line$j, "extends ", (node.extends.length === 1 ? identity : indent$f)(join$g([",", line$j], path.map(print, "extends"))));
}
- if (!n.property || isNumericLiteral$2(n.property)) {
- return concat$o([optional, "[", property, "]"]);
+ if (node.id && hasComment$5(node.id, CommentCheckFlags$5.Trailing) || isNonEmptyArray$a(node.extends)) {
+ if (shouldIndentOnlyHeritageClauses) {
+ parts.push(group$k([...partsGroup, indent$f(extendsParts)]));
+ } else {
+ parts.push(group$k(indent$f([...partsGroup, ...extendsParts])));
+ }
+ } else {
+ parts.push(...partsGroup, ...extendsParts);
}
- return group$f(concat$o([optional, "[", indent$j(concat$o([softline$f, property])), softline$f, "]"]));
+ parts.push(" ", print("body"));
+ return group$k(parts);
}
-var member = {
- printMemberExpression,
- printMemberLookup
+var _interface = {
+ printInterface: printInterface$2
};
const {
- getLast: getLast$7,
- isNextLineEmpty: isNextLineEmpty$6,
- isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$4
-} = util;
-const {
- hasLeadingComment: hasLeadingComment$4,
- hasTrailingComment: hasTrailingComment$4,
- isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$2,
- isFunctionOrArrowExpression: isFunctionOrArrowExpression$1,
- isLongCurriedCallExpression: isLongCurriedCallExpression$2,
- isMemberish: isMemberish$1,
- isNumericLiteral: isNumericLiteral$3,
- isSimpleCallArgument: isSimpleCallArgument$1
-} = utils$6;
-const {
- locEnd: locEnd$a
-} = loc;
+ isNonEmptyArray: isNonEmptyArray$9
+} = util$8;
const {
builders: {
- concat: concat$p,
- join: join$9,
- hardline: hardline$g,
- group: group$g,
- indent: indent$k,
- conditionalGroup: conditionalGroup$3,
- breakParent: breakParent$4
- },
- utils: {
- willBreak: willBreak$3
+ softline: softline$f,
+ group: group$j,
+ indent: indent$e,
+ join: join$f,
+ line: line$i,
+ ifBreak: ifBreak$c,
+ hardline: hardline$n
}
-} = document;
+} = require$$7$3;
const {
- printMemberLookup: printMemberLookup$1
-} = member;
+ printDanglingComments: printDanglingComments$5
+} = comments$4;
const {
- printOptionalToken: printOptionalToken$4,
- printFunctionTypeParameters: printFunctionTypeParameters$3,
- printBindExpressionCallee: printBindExpressionCallee$1
-} = misc; // 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, options, print) {
- const parent = path.getParentNode();
- const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; // 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]
-
- const 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
+ hasComment: hasComment$4,
+ CommentCheckFlags: CommentCheckFlags$4,
+ shouldPrintComma: shouldPrintComma$4,
+ needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1
+} = utils$5;
+const {
+ locStart: locStart$l,
+ hasSameLoc
+} = loc$6;
+const {
+ hasDecoratorsBeforeExport,
+ printDecoratorsBeforeExport
+} = decorators;
+/**
+ * @typedef {import("../../document").Doc} Doc
+ */
- function shouldInsertEmptyLineAfter(node) {
- const {
- originalText
- } = options;
- const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$4(originalText, node, locEnd$a);
- const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
- // line after that parenthesis
+function printImportDeclaration$1(path, options, print) {
+ const node = path.getValue();
+ const semi = options.semi ? ";" : "";
+ /** @type{Doc[]} */
- if (nextChar === ")") {
- return nextCharIndex !== false && isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1);
- }
+ const parts = [];
+ const {
+ importKind
+ } = node;
+ parts.push("import");
- return isNextLineEmpty$6(originalText, node, locEnd$a);
+ if (importKind && importKind !== "value") {
+ parts.push(" ", importKind);
}
- function rec(path) {
- const node = path.getValue();
+ parts.push(printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print), semi);
+ return parts;
+}
- if (isCallOrOptionalCallExpression$2(node) && (isMemberish$1(node.callee) || isCallOrOptionalCallExpression$2(node.callee))) {
- printedNodes.unshift({
- node,
- printed: concat$p([comments.printComments(path, () => concat$p([printOptionalToken$4(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$g : ""])
- });
- path.call(callee => rec(callee), "callee");
- } else if (isMemberish$1(node)) {
- printedNodes.unshift({
- node,
- needsParens: needsParens_1(path, options),
- printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup$1(path, options, print) : printBindExpressionCallee$1(path, options, print), options)
- });
- path.call(object => rec(object), "object");
- } else if (node.type === "TSNonNullExpression") {
- printedNodes.unshift({
- node,
- printed: comments.printComments(path, () => "!", options)
- });
- path.call(expression => rec(expression), "expression");
- } else {
- printedNodes.unshift({
- node,
- printed: path.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.
+function printExportDeclaration$2(path, options, print) {
+ const node = path.getValue();
+ /** @type{Doc[]} */
+ const parts = []; // Only print decorators here if they were written before the export,
+ // otherwise they are printed by the node.declaration
- const node = path.getValue();
- printedNodes.unshift({
- node,
- printed: concat$p([printOptionalToken$4(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)])
- });
+ if (hasDecoratorsBeforeExport(node)) {
+ parts.push(printDecoratorsBeforeExport(path, options, print));
+ }
- if (node.callee) {
- path.call(callee => 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 accessors as possible
- // < fn()[0][1][2] >.something()
- // - then, as many MemberExpression as possible but the last one
- // < this.items >.something()
+ const {
+ type,
+ exportKind,
+ declaration
+ } = node;
+ parts.push("export");
+ const isDefaultExport = node.default || type === "ExportDefaultDeclaration";
+ if (isDefaultExport) {
+ parts.push(" default");
+ }
- const groups = [];
- let currentGroup = [printedNodes[0]];
- let i = 1;
+ if (hasComment$4(node, CommentCheckFlags$4.Dangling)) {
+ parts.push(" ", printDanglingComments$5(path, options,
+ /* sameIndent */
+ true));
- for (; i < printedNodes.length; ++i) {
- if (printedNodes[i].node.type === "TSNonNullExpression" || isCallOrOptionalCallExpression$2(printedNodes[i].node) || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$3(printedNodes[i].node.property)) {
- currentGroup.push(printedNodes[i]);
- } else {
- break;
+ if (needsHardlineAfterDanglingComment$1(node)) {
+ parts.push(hardline$n);
}
}
- if (!isCallOrOptionalCallExpression$2(printedNodes[0].node)) {
- for (; i + 1 < printedNodes.length; ++i) {
- if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
- currentGroup.push(printedNodes[i]);
- } else {
- break;
- }
- }
+ if (declaration) {
+ parts.push(" ", print("declaration"));
+ } else {
+ parts.push(exportKind === "type" ? " type" : "", printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print));
}
- 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
+ if (shouldExportDeclarationPrintSemi(node, options)) {
+ parts.push(";");
+ }
- let hasSeenCallExpression = false;
+ return parts;
+}
- for (; i < printedNodes.length; ++i) {
- if (hasSeenCallExpression && isMemberish$1(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$3(printedNodes[i].node.property)) {
- currentGroup.push(printedNodes[i]);
- continue;
- }
+function printExportAllDeclaration$2(path, options, print) {
+ const node = path.getValue();
+ const semi = options.semi ? ";" : "";
+ /** @type{Doc[]} */
- groups.push(currentGroup);
- currentGroup = [];
- hasSeenCallExpression = false;
- }
+ const parts = [];
+ const {
+ exportKind,
+ exported
+ } = node;
+ parts.push("export");
- if (isCallOrOptionalCallExpression$2(printedNodes[i].node) || printedNodes[i].node.type === "ImportExpression") {
- hasSeenCallExpression = true;
- }
+ if (exportKind === "type") {
+ parts.push(" type");
+ }
- currentGroup.push(printedNodes[i]);
+ parts.push(" *");
- if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
- groups.push(currentGroup);
- currentGroup = [];
- hasSeenCallExpression = false;
- }
+ if (exported) {
+ parts.push(" as ", print("exported"));
+ }
+
+ parts.push(printModuleSource(path, options, print), printImportAssertions(path, options, print), semi);
+ return parts;
+}
+
+function shouldExportDeclarationPrintSemi(node, options) {
+ if (!options.semi) {
+ return false;
+ }
+
+ const {
+ type,
+ declaration
+ } = node;
+ const isDefaultExport = node.default || type === "ExportDefaultDeclaration";
+
+ if (!declaration) {
+ return true;
}
- 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.
+ const {
+ type: declarationType
+ } = declaration;
+ if (isDefaultExport && declarationType !== "ClassDeclaration" && declarationType !== "FunctionDeclaration" && declarationType !== "TSInterfaceDeclaration" && declarationType !== "DeclareClass" && declarationType !== "DeclareFunction" && declarationType !== "TSDeclareFunction" && declarationType !== "EnumDeclaration") {
+ return true;
+ }
- 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]);
- //
+ return false;
+}
+function printModuleSource(path, options, print) {
+ const node = path.getValue();
- function isShort(name) {
- return name.length <= options.tabWidth;
+ if (!node.source) {
+ return "";
}
+ /** @type{Doc[]} */
- function shouldNotWrap(groups) {
- const hasComputed = groups[1].length && groups[1][0].node.computed;
- if (groups[0].length === 1) {
- const firstNode = groups[0][0].node;
- return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed);
- }
+ const parts = [];
- const lastNode = getLast$7(groups[0]).node;
- return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
+ if (!shouldNotPrintSpecifiers(node, options)) {
+ parts.push(" from");
}
- const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
-
- function printGroup(printedGroup) {
- const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
- // accordingly
+ parts.push(" ", print("source"));
+ return parts;
+}
- if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
- return concat$p(["(", ...printed, ")"]);
- }
+function printModuleSpecifiers(path, options, print) {
+ const node = path.getValue();
- return concat$p(printed);
+ if (shouldNotPrintSpecifiers(node, options)) {
+ return "";
}
+ /** @type{Doc[]} */
- function printIndentedGroup(groups) {
- /* istanbul ignore next */
- if (groups.length === 0) {
- return "";
- }
- return indent$k(group$g(concat$p([hardline$g, join$9(hardline$g, groups.map(printGroup))])));
- }
+ const parts = [" "];
- const printedGroups = groups.map(printGroup);
- const oneLine = concat$p(printedGroups);
- const cutoff = shouldMerge ? 3 : 2;
- const flatGroups = flatten_1(groups);
- const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$4(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$4(node.node)) || groups[cutoff] && hasLeadingComment$4(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
- // render everything concatenated together.
+ if (isNonEmptyArray$9(node.specifiers)) {
+ const standaloneSpecifiers = [];
+ const groupedSpecifiers = [];
+ path.each(() => {
+ const specifierType = path.getValue().type;
- if (groups.length <= cutoff && !hasComment) {
- if (isLongCurriedCallExpression$2(path)) {
- return oneLine;
- }
+ if (specifierType === "ExportNamespaceSpecifier" || specifierType === "ExportDefaultSpecifier" || specifierType === "ImportNamespaceSpecifier" || specifierType === "ImportDefaultSpecifier") {
+ standaloneSpecifiers.push(print());
+ } else if (specifierType === "ExportSpecifier" || specifierType === "ImportSpecifier") {
+ groupedSpecifiers.push(print());
+ } else {
+ /* istanbul ignore next */
+ throw new Error(`Unknown specifier type ${JSON.stringify(specifierType)}`);
+ }
+ }, "specifiers");
+ parts.push(join$f(", ", standaloneSpecifiers));
- return group$g(oneLine);
- } // Find out the last node in the first group and check if it has an
- // empty line after
+ if (groupedSpecifiers.length > 0) {
+ if (standaloneSpecifiers.length > 0) {
+ parts.push(", ");
+ }
+ const canBreak = groupedSpecifiers.length > 1 || standaloneSpecifiers.length > 0 || node.specifiers.some(node => hasComment$4(node));
- const lastNodeBeforeIndent = getLast$7(groups[shouldMerge ? 1 : 0]).node;
- const shouldHaveEmptyLineBeforeIndent = !isCallOrOptionalCallExpression$2(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
- const expanded = concat$p([printGroup(groups[0]), shouldMerge ? concat$p(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$g : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
- const callExpressions = printedNodes.map(({
- node
- }) => node).filter(isCallOrOptionalCallExpression$2);
+ if (canBreak) {
+ parts.push(group$j(["{", indent$e([options.bracketSpacing ? line$i : softline$f, join$f([",", line$i], groupedSpecifiers)]), ifBreak$c(shouldPrintComma$4(options) ? "," : ""), options.bracketSpacing ? line$i : softline$f, "}"]));
+ } else {
+ parts.push(["{", options.bracketSpacing ? " " : "", ...groupedSpecifiers, options.bracketSpacing ? " " : "", "}"]);
+ }
+ }
+ } else {
+ parts.push("{}");
+ }
- function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
- const lastGroupNode = getLast$7(getLast$7(groups)).node;
- const lastGroupDoc = getLast$7(printedGroups);
- return isCallOrOptionalCallExpression$2(lastGroupNode) && willBreak$3(lastGroupDoc) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1));
- } // We don't want to print in one line if at least one of these conditions occurs:
- // * the chain has comments,
- // * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern),
- // * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one,
- // * any group but the last one has a hard line,
- // * the last call's arguments have a hard line and other calls have non-trivial arguments.
+ return parts;
+}
+function shouldNotPrintSpecifiers(node, options) {
+ const {
+ type,
+ importKind,
+ source,
+ specifiers
+ } = node;
+
+ if (type !== "ImportDeclaration" || isNonEmptyArray$9(specifiers) || importKind === "type") {
+ return false;
+ } // TODO: check tokens
- if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$3) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) {
- return group$g(expanded);
- }
- return concat$p([// We only need to check `oneLine` because if `expanded` is chosen
- // that means that the parent group has already been broken
- // naturally
- willBreak$3(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$4 : "", conditionalGroup$3([oneLine, expanded])]);
+ return !/{\s*}/.test(options.originalText.slice(locStart$l(node), locStart$l(source)));
}
-var memberChain = printMemberChain;
+function printImportAssertions(path, options, print) {
+ const node = path.getNode();
-const {
- builders: {
- concat: concat$q,
- join: join$a,
- group: group$h
+ if (isNonEmptyArray$9(node.assertions)) {
+ return [" assert {", options.bracketSpacing ? " " : "", join$f(", ", path.map(print, "assertions")), options.bracketSpacing ? " " : "", "}"];
}
-} = document;
-const {
- getCallArguments: getCallArguments$2,
- hasFlowAnnotationComment: hasFlowAnnotationComment$2,
- isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$3,
- isMemberish: isMemberish$2,
- isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$2,
- isTestCall: isTestCall$3,
- iterateCallArgumentsPath: iterateCallArgumentsPath$2
-} = utils$6;
-const {
- printOptionalToken: printOptionalToken$5,
- printFunctionTypeParameters: printFunctionTypeParameters$4
-} = misc;
-function printCallExpression(path, options, print) {
- const n = path.getValue();
- const isNew = n.type === "NewExpression";
- const isDynamicImport = n.type === "ImportExpression";
- const optional = printOptionalToken$5(path);
- const args = getCallArguments$2(n);
+ return "";
+}
- if ( // Dangling comments not handled, all these special cases should has argument #9668
- args.length > 0 && ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
- // define calls, as a unit.
- // e.g. `define(["some/lib", (lib) => {`
- !isDynamicImport && !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
- args.length === 1 && isTemplateOnItsOwnLine$2(args[0], options.originalText) || // Keep test declarations on a single line
- // e.g. `it('long name', () => {`
- !isNew && isTestCall$3(n, path.getParentNode()))) {
- const printed = [];
- iterateCallArgumentsPath$2(path, argPath => {
- printed.push(print(argPath));
- });
- return concat$q([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters$4(path, options, print), concat$q(["(", join$a(", ", printed), ")"])]);
- } // Inline Flow annotation comments following Identifiers in Call nodes need to
- // stay with the Identifier. For example:
- //
- // foo /*:: */(bar);
- //
- // Here, we ensure that such comments stay between the Identifier and the Callee.
+function printModuleSpecifier$1(path, options, print) {
+ const node = path.getNode();
+ const {
+ type
+ } = node;
+ /** @type {Doc[]} */
+ const parts = [];
+ /** @type {"type" | "typeof" | "value"} */
- const isIdentifierWithFlowAnnotation = (options.parser === "babel" || options.parser === "babel-flow") && n.callee && n.callee.type === "Identifier" && hasFlowAnnotationComment$2(n.callee.trailingComments);
+ const kind = type === "ImportSpecifier" ? node.importKind : node.exportKind;
- if (isIdentifierWithFlowAnnotation) {
- n.callee.trailingComments[0].printed = true;
- } // We detect calls on member lookups and possibly print them in a
- // special chain format. See `printMemberChain` for more info.
+ if (kind && kind !== "value") {
+ parts.push(kind, " ");
+ }
+ const isImport = type.startsWith("Import");
+ const leftSideProperty = isImport ? "imported" : "local";
+ const rightSideProperty = isImport ? "local" : "exported";
+ let left = "";
+ let right = "";
- if (!isDynamicImport && !isNew && isMemberish$2(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
- return memberChain(path, options, print);
+ if (type === "ExportNamespaceSpecifier" || type === "ImportNamespaceSpecifier") {
+ left = "*";
+ } else if (node[leftSideProperty]) {
+ left = print(leftSideProperty);
}
- const contents = concat$q([isNew ? "new " : "", isDynamicImport ? "import" : path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters$4(path, options, print), callArguments(path, options, print)]); // We group here when the callee is itself a call expression.
- // See `isLongCurriedCallExpression` for more info.
-
- if (isDynamicImport || isCallOrOptionalCallExpression$3(n.callee)) {
- return group$h(contents);
+ if (node[rightSideProperty] && (!node[leftSideProperty] || // import {a as a} from '.'
+ !hasSameLoc(node[leftSideProperty], node[rightSideProperty]))) {
+ right = print(rightSideProperty);
}
- return contents;
+ parts.push(left, left && right ? " as " : "", right);
+ return parts;
}
-var callExpression = {
- printCallExpression
+var module$1 = {
+ printImportDeclaration: printImportDeclaration$1,
+ printExportDeclaration: printExportDeclaration$2,
+ printExportAllDeclaration: printExportAllDeclaration$2,
+ printModuleSpecifier: printModuleSpecifier$1
};
+const {
+ printDanglingComments: printDanglingComments$4
+} = comments$4;
const {
builders: {
- concat: concat$r,
- join: join$b,
- line: line$g,
+ line: line$h,
+ softline: softline$e,
group: group$i,
- indent: indent$l,
- ifBreak: ifBreak$b
+ indent: indent$d,
+ ifBreak: ifBreak$b,
+ hardline: hardline$m
}
-} = document;
+} = require$$7$3;
const {
- hasTrailingComment: hasTrailingComment$5,
- hasTrailingLineComment: hasTrailingLineComment$2,
- identity: identity$2
-} = utils$6;
+ getLast: getLast$a,
+ hasNewlineInRange: hasNewlineInRange$2,
+ hasNewline: hasNewline$3,
+ isNonEmptyArray: isNonEmptyArray$8
+} = util$8;
const {
- getTypeParametersGroupId: getTypeParametersGroupId$2
-} = typeParameters;
+ shouldPrintComma: shouldPrintComma$3,
+ hasComment: hasComment$3,
+ getComments: getComments$1,
+ CommentCheckFlags: CommentCheckFlags$3,
+ isNextLineEmpty: isNextLineEmpty$7
+} = utils$5;
const {
- printTypeScriptModifiers: printTypeScriptModifiers$1
-} = misc;
+ locStart: locStart$k,
+ locEnd: locEnd$j
+} = loc$6;
+const {
+ printOptionalToken: printOptionalToken$3,
+ printTypeAnnotation: printTypeAnnotation$2
+} = misc$1;
+const {
+ shouldHugFunctionParameters
+} = functionParameters;
+const {
+ shouldHugType
+} = typeAnnotation;
+const {
+ printHardlineAfterHeritage: printHardlineAfterHeritage$1
+} = _class;
+/** @typedef {import("../../document").Doc} Doc */
-function printInterface(path, options, print) {
- const n = path.getValue();
- const parts = [];
+function printObject$3(path, options, print) {
+ const semi = options.semi ? ";" : "";
+ const node = path.getValue();
+ let propertiesField;
- if (n.type === "DeclareInterface" || n.declare) {
- parts.push("declare ");
+ if (node.type === "TSTypeLiteral") {
+ propertiesField = "members";
+ } else if (node.type === "TSInterfaceBody") {
+ propertiesField = "body";
+ } else {
+ propertiesField = "properties";
}
- if (n.type === "TSInterfaceDeclaration") {
- parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers$1(path, options, print));
+ const isTypeAnnotation = node.type === "ObjectTypeAnnotation";
+ const fields = [propertiesField];
+
+ if (isTypeAnnotation) {
+ fields.push("indexers", "callProperties", "internalSlots");
}
- parts.push("interface");
- const partsGroup = [];
- const extendsParts = [];
+ const firstProperty = fields.map(field => node[field][0]).sort((a, b) => locStart$k(a) - locStart$k(b))[0];
+ const parent = path.getParentNode(0);
+ const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
+ const shouldBreak = node.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || node.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && node.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || node.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$2(options.originalText, locStart$k(node), locStart$k(firstProperty));
+ const separator = isFlowInterfaceLikeBody ? ";" : node.type === "TSInterfaceBody" || node.type === "TSTypeLiteral" ? ifBreak$b(semi, ";") : ",";
+ const leftBrace = node.type === "RecordExpression" ? "#{" : node.exact ? "{|" : "{";
+ const rightBrace = node.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
+ // interleaved in the source code. So we need to reorder them before
+ // printing them.
- if (n.type !== "InterfaceTypeAnnotation") {
- partsGroup.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
- }
+ const propsAndLoc = [];
- const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$2(n.typeParameters);
+ for (const field of fields) {
+ path.each(childPath => {
+ const node = childPath.getValue();
+ propsAndLoc.push({
+ node,
+ printed: print(),
+ loc: locStart$k(node)
+ });
+ }, field);
+ }
- if (n.extends && n.extends.length !== 0) {
- extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$b(" ", line$g, {
- groupId: getTypeParametersGroupId$2(n.typeParameters)
- }) : line$g, "extends ", (n.extends.length === 1 ? identity$2 : indent$l)(join$b(concat$r([",", line$g]), path.map(print, "extends"))));
+ if (fields.length > 1) {
+ propsAndLoc.sort((a, b) => a.loc - b.loc);
}
+ /** @type {Doc[]} */
- if (n.id && hasTrailingComment$5(n.id) || n.extends && n.extends.length !== 0) {
- const printedExtends = concat$r(extendsParts);
- if (shouldIndentOnlyHeritageClauses) {
- parts.push(group$i(concat$r(partsGroup.concat(ifBreak$b(indent$l(printedExtends), printedExtends)))));
+ let separatorParts = [];
+ const props = propsAndLoc.map(prop => {
+ const result = [...separatorParts, group$i(prop.printed)];
+ separatorParts = [separator, line$h];
+
+ if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasComment$3(prop.node, CommentCheckFlags$3.PrettierIgnore)) {
+ separatorParts.shift();
+ }
+
+ if (isNextLineEmpty$7(prop.node, options)) {
+ separatorParts.push(hardline$m);
+ }
+
+ return result;
+ });
+
+ if (node.inexact) {
+ let printed;
+
+ if (hasComment$3(node, CommentCheckFlags$3.Dangling)) {
+ const hasLineComments = hasComment$3(node, CommentCheckFlags$3.Line);
+ const printedDanglingComments = printDanglingComments$4(path, options,
+ /* sameIndent */
+ true);
+ printed = [printedDanglingComments, hasLineComments || hasNewline$3(options.originalText, locEnd$j(getLast$a(getComments$1(node)))) ? hardline$m : line$h, "..."];
} else {
- parts.push(group$i(indent$l(concat$r(partsGroup.concat(printedExtends)))));
+ printed = ["..."];
+ }
+
+ props.push([...separatorParts, ...printed]);
+ }
+
+ const lastElem = getLast$a(node[propertiesField]);
+ const canHaveTrailingSeparator = !(node.inexact || lastElem && lastElem.type === "RestElement" || lastElem && (lastElem.type === "TSPropertySignature" || lastElem.type === "TSCallSignatureDeclaration" || lastElem.type === "TSMethodSignature" || lastElem.type === "TSConstructSignatureDeclaration") && hasComment$3(lastElem, CommentCheckFlags$3.PrettierIgnore));
+ let content;
+
+ if (props.length === 0) {
+ if (!hasComment$3(node, CommentCheckFlags$3.Dangling)) {
+ return [leftBrace, rightBrace, printTypeAnnotation$2(path, options, print)];
}
+
+ content = group$i([leftBrace, printDanglingComments$4(path, options), softline$e, rightBrace, printOptionalToken$3(path), printTypeAnnotation$2(path, options, print)]);
} else {
- parts.push(...partsGroup, ...extendsParts);
+ content = [isFlowInterfaceLikeBody && isNonEmptyArray$8(node.properties) ? printHardlineAfterHeritage$1(parent) : "", leftBrace, indent$d([options.bracketSpacing ? line$h : softline$e, ...props]), ifBreak$b(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$3(options)) ? separator : ""), options.bracketSpacing ? line$h : softline$e, rightBrace, printOptionalToken$3(path), printTypeAnnotation$2(path, options, print)];
+ } // If we inline the object as first argument of the parent, we don't want
+ // to create another group so that the object breaks before the return
+ // type
+
+
+ if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugFunctionParameters(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugFunctionParameters(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || // Assignment printing logic (printAssignment) is responsible
+ // for adding a group if needed
+ !shouldBreak && path.match(node => node.type === "ObjectPattern", node => node.type === "AssignmentExpression" || node.type === "VariableDeclarator")) {
+ return content;
}
- parts.push(" ", path.call(print, "body"));
- return group$i(concat$r(parts));
+ return group$i(content, {
+ shouldBreak
+ });
}
-var _interface = {
- printInterface
+var object$1 = {
+ printObject: printObject$3
};
+/** @typedef {import("../../document").Doc} Doc */
+
+
+const assert$1 = require$$0__default$3["default"];
const {
- printComments: printComments$4
-} = comments;
+ printDanglingComments: printDanglingComments$3
+} = comments$4;
const {
- getLast: getLast$8
-} = util;
+ printString: printString$2,
+ printNumber: printNumber$2
+} = util$8;
const {
builders: {
- concat: concat$s,
- join: join$c,
- line: line$h,
- softline: softline$g,
- group: group$j,
- indent: indent$m,
- align: align$3,
- ifBreak: ifBreak$c
- },
- utils: {
- normalizeParts: normalizeParts$1
+ hardline: hardline$l,
+ softline: softline$d,
+ group: group$h,
+ indent: indent$c
}
-} = document;
+} = require$$7$3;
const {
- hasLeadingOwnLineComment: hasLeadingOwnLineComment$2,
- hasTrailingLineComment: hasTrailingLineComment$3,
- isBinaryish: isBinaryish$4,
- isJSXNode: isJSXNode$6,
- shouldFlatten: shouldFlatten$2
-} = utils$6;
-/** @typedef {import("../../document").Doc} Doc */
+ getParentExportDeclaration,
+ isFunctionNotation,
+ isGetterOrSetter,
+ rawText: rawText$1,
+ shouldPrintComma: shouldPrintComma$2
+} = utils$5;
+const {
+ locStart: locStart$j,
+ locEnd: locEnd$i
+} = loc$6;
+const {
+ printClass: printClass$1
+} = _class;
+const {
+ printOpaqueType,
+ printTypeAlias: printTypeAlias$1,
+ printIntersectionType: printIntersectionType$1,
+ printUnionType: printUnionType$1,
+ printFunctionType: printFunctionType$1,
+ printTupleType: printTupleType$1,
+ printIndexedAccessType: printIndexedAccessType$1
+} = typeAnnotation;
+const {
+ printInterface: printInterface$1
+} = _interface;
+const {
+ printTypeParameter: printTypeParameter$1,
+ printTypeParameters: printTypeParameters$1
+} = typeParameters;
+const {
+ printExportDeclaration: printExportDeclaration$1,
+ printExportAllDeclaration: printExportAllDeclaration$1
+} = module$1;
+const {
+ printArrayItems: printArrayItems$1
+} = array;
+const {
+ printObject: printObject$2
+} = object$1;
+const {
+ printPropertyKey: printPropertyKey$1
+} = property;
+const {
+ printOptionalToken: printOptionalToken$2,
+ printTypeAnnotation: printTypeAnnotation$1,
+ printRestSpread: printRestSpread$1
+} = misc$1;
-let uid = 0;
+function printFlow$1(path, options, print) {
+ const node = path.getValue();
+ const semi = options.semi ? ";" : "";
+ /** @type{Doc[]} */
-function printBinaryishExpression(path, options, print) {
- const n = path.getValue();
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
- const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement");
- const parts = printBinaryishExpressions(path, print, options,
- /* isNested */
- false, isInsideParenthesis); // if (
- // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
- // ) {
- //
- // looks super weird, we want to break the children if the parent breaks
- //
- // if (
- // this.hasPlugin("dynamicImports") &&
- // this.lookahead().type === tt.parenLeft
- // ) {
+ const parts = [];
- if (isInsideParenthesis) {
- return concat$s(parts);
- } // Break between the parens in
- // unaries or in a member or specific call expression, i.e.
- //
- // (
- // a &&
- // b &&
- // c
- // ).call()
+ switch (node.type) {
+ case "DeclareClass":
+ return printFlowDeclaration(path, printClass$1(path, options, print));
+ case "DeclareFunction":
+ return printFlowDeclaration(path, ["function ", print("id"), node.predicate ? " " : "", print("predicate"), semi]);
- if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) {
- return group$j(concat$s([indent$m(concat$s([softline$g, concat$s(parts)])), softline$g]));
- } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
- // indented accordingly. We should indent sub-expressions where the first case isn't indented.
+ case "DeclareModule":
+ return printFlowDeclaration(path, ["module ", print("id"), " ", print("body")]);
+ case "DeclareModuleExports":
+ return printFlowDeclaration(path, ["module.exports", ": ", print("typeAnnotation"), semi]);
- const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral";
- const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "FieldDefinition" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property";
- const samePrecedenceSubExpression = isBinaryish$4(n.left) && shouldFlatten$2(n.operator, n.left.operator);
+ case "DeclareVariable":
+ return printFlowDeclaration(path, ["var ", print("id"), semi]);
- if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
- return group$j(concat$s(parts));
- }
+ case "DeclareOpaqueType":
+ return printFlowDeclaration(path, printOpaqueType(path, options, print));
- if (parts.length === 0) {
- return "";
- } // If the right part is a JSX node, we include it in a separate group to
- // prevent it breaking the whole chain, so we can print the expression like:
- //
- // foo && bar && (
- //
- //
- //
- // )
+ case "DeclareInterface":
+ return printFlowDeclaration(path, printInterface$1(path, options, print));
+ case "DeclareTypeAlias":
+ return printFlowDeclaration(path, printTypeAlias$1(path, options, print));
- const hasJSX = isJSXNode$6(n.right);
- const firstGroupIndex = parts.findIndex(part => typeof part !== "string" && part.type === "group"); // Separate the leftmost expression, possibly with its leading comments.
+ case "DeclareExportDeclaration":
+ return printFlowDeclaration(path, printExportDeclaration$1(path, options, print));
- const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1);
- const rest = concat$s(parts.slice(headParts.length, hasJSX ? -1 : undefined));
- const groupId = Symbol("logicalChain-" + ++uid);
- const chain = group$j(concat$s([// Don't include the initial expression in the indentation
- // level. The first item is guaranteed to be the first
- // left-most expression.
- ...headParts, indent$m(rest)]), {
- id: groupId
- });
+ case "DeclareExportAllDeclaration":
+ return printFlowDeclaration(path, printExportAllDeclaration$1(path, options, print));
- if (!hasJSX) {
- return chain;
- }
+ case "OpaqueType":
+ return printOpaqueType(path, options, print);
- const jsxPart = getLast$8(parts);
- return group$j(concat$s([chain, ifBreak$c(indent$m(jsxPart), jsxPart, {
- groupId
- })]));
-} // 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 `+`.
+ case "TypeAlias":
+ return printTypeAlias$1(path, options, print);
+ case "IntersectionTypeAnnotation":
+ return printIntersectionType$1(path, options, print);
-function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
- /** @type{Doc[]} */
- let parts = [];
- const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
-
- if (isBinaryish$4(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$2(node.operator, node.left.operator)) {
- // Flatten them out by recursively calling this function.
- parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
- /* isNested */
- true, isInsideParenthesis), "left"));
- } else {
- parts.push(group$j(path.call(print, "left")));
- }
+ case "UnionTypeAnnotation":
+ return printUnionType$1(path, options, print);
- const shouldInline = shouldInlineLogicalExpression(node);
- const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$2(options.originalText, node.right);
- const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
- const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$j(indent$m(concat$s([softline$g, ": ", join$c(concat$s([softline$g, ":", ifBreak$c(" ")]), path.map(print, "arguments").map(arg => align$3(2, group$j(arg))))]))) : "";
- const right = shouldInline ? concat$s([operator, " ", path.call(print, "right"), rightSuffix]) : concat$s([lineBeforeOperator ? line$h : "", operator, lineBeforeOperator ? " " : line$h, path.call(print, "right"), rightSuffix]); // 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.
+ case "FunctionTypeAnnotation":
+ return printFunctionType$1(path, options, print);
- const parent = path.getParentNode();
- const shouldBreak = hasTrailingLineComment$3(node.left);
- const shouldGroup = shouldBreak || !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
- parts.push(lineBeforeOperator ? "" : " ", shouldGroup ? group$j(right, {
- shouldBreak
- }) : 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
+ case "TupleTypeAnnotation":
+ return printTupleType$1(path, options, print);
- if (isNested && node.comments) {
- parts = normalizeParts$1(printComments$4(path, () => concat$s(parts), options).parts);
- }
- } else {
- // Our stopping case. Simply print the node normally.
- parts.push(group$j(path.call(print)));
- }
+ case "GenericTypeAnnotation":
+ return [print("id"), printTypeParameters$1(path, options, print, "typeParameters")];
- return parts;
-}
+ case "IndexedAccessType":
+ case "OptionalIndexedAccessType":
+ return printIndexedAccessType$1(path, options, print);
+ // Type Annotations for Facebook Flow, typically stripped out or
+ // transformed away before printing.
-function shouldInlineLogicalExpression(node) {
- if (node.type !== "LogicalExpression") {
- return false;
- }
+ case "TypeAnnotation":
+ return print("typeAnnotation");
- if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
- return true;
- }
+ case "TypeParameter":
+ return printTypeParameter$1(path, options, print);
- if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
- return true;
- }
+ case "TypeofTypeAnnotation":
+ return ["typeof ", print("argument")];
- if (isJSXNode$6(node.right)) {
- return true;
- }
+ case "ExistsTypeAnnotation":
+ return "*";
- return false;
-}
+ case "EmptyTypeAnnotation":
+ return "empty";
-var binaryish = {
- printBinaryishExpression,
- shouldInlineLogicalExpression
-};
+ case "MixedTypeAnnotation":
+ return "mixed";
-const {
- builders: {
- concat: concat$t,
- line: line$i,
- group: group$k,
- indent: indent$n
- }
-} = document;
-const {
- hasLeadingOwnLineComment: hasLeadingOwnLineComment$3,
- isBinaryish: isBinaryish$5,
- isMemberExpressionChain: isMemberExpressionChain$1,
- isStringLiteral: isStringLiteral$3
-} = utils$6;
-const {
- shouldInlineLogicalExpression: shouldInlineLogicalExpression$1
-} = binaryish;
+ case "ArrayTypeAnnotation":
+ return [print("elementType"), "[]"];
-function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
- if (!rightNode) {
- return printedLeft;
- }
+ case "BooleanLiteralTypeAnnotation":
+ return String(node.value);
- const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
- return group$k(concat$t([printedLeft, operator, printed]));
-}
+ case "EnumDeclaration":
+ return ["enum ", print("id"), " ", print("body")];
-function printAssignmentExpression(path, options, print) {
- const n = path.getValue();
- return printAssignment(n.left, path.call(print, "left"), concat$t([" ", n.operator]), n.right, path.call(print, "right"), options);
-}
+ case "EnumBooleanBody":
+ case "EnumNumberBody":
+ case "EnumStringBody":
+ case "EnumSymbolBody":
+ {
+ if (node.type === "EnumSymbolBody" || node.explicitType) {
+ let type = null;
-function printVariableDeclarator(path, options, print) {
- const n = path.getValue();
- return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
-}
+ switch (node.type) {
+ case "EnumBooleanBody":
+ type = "boolean";
+ break;
+
+ case "EnumNumberBody":
+ type = "number";
+ break;
+
+ case "EnumStringBody":
+ type = "string";
+ break;
+
+ case "EnumSymbolBody":
+ type = "symbol";
+ break;
+ }
+
+ parts.push("of ", type, " ");
+ }
+
+ if (node.members.length === 0 && !node.hasUnknownMembers) {
+ parts.push(group$h(["{", printDanglingComments$3(path, options), softline$d, "}"]));
+ } else {
+ const members = node.members.length > 0 ? [hardline$l, printArrayItems$1(path, options, "members", print), node.hasUnknownMembers || shouldPrintComma$2(options) ? "," : ""] : [];
+ parts.push(group$h(["{", indent$c([...members, ...(node.hasUnknownMembers ? [hardline$l, "..."] : [])]), printDanglingComments$3(path, options,
+ /* sameIndent */
+ true), hardline$l, "}"]));
+ }
+
+ return parts;
+ }
+
+ case "EnumBooleanMember":
+ case "EnumNumberMember":
+ case "EnumStringMember":
+ return [print("id"), " = ", typeof node.init === "object" ? print("init") : String(node.init)];
+
+ case "EnumDefaultedMember":
+ return print("id");
+
+ case "FunctionTypeParam":
+ {
+ const name = node.name ? print("name") : path.getParentNode().this === node ? "this" : "";
+ return [name, printOptionalToken$2(path), name ? ": " : "", print("typeAnnotation")];
+ }
+
+ case "InterfaceDeclaration":
+ case "InterfaceTypeAnnotation":
+ return printInterface$1(path, options, print);
+
+ case "ClassImplements":
+ case "InterfaceExtends":
+ return [print("id"), print("typeParameters")];
+
+ case "NullableTypeAnnotation":
+ return ["?", print("typeAnnotation")];
+
+ case "Variance":
+ {
+ const {
+ kind
+ } = node;
+ assert$1.ok(kind === "plus" || kind === "minus");
+ return kind === "plus" ? "+" : "-";
+ }
+
+ case "ObjectTypeCallProperty":
+ if (node.static) {
+ parts.push("static ");
+ }
+
+ parts.push(print("value"));
+ return parts;
+
+ case "ObjectTypeIndexer":
+ {
+ return [node.variance ? print("variance") : "", "[", print("id"), node.id ? ": " : "", print("key"), "]: ", print("value")];
+ }
+
+ case "ObjectTypeProperty":
+ {
+ let modifier = "";
+
+ if (node.proto) {
+ modifier = "proto ";
+ } else if (node.static) {
+ modifier = "static ";
+ }
-function printAssignmentRight(leftNode, rightNode, printedRight, options) {
- if (hasLeadingOwnLineComment$3(options.originalText, rightNode)) {
- return indent$n(concat$t([line$i, printedRight]));
- }
+ return [modifier, isGetterOrSetter(node) ? node.kind + " " : "", node.variance ? print("variance") : "", printPropertyKey$1(path, options, print), printOptionalToken$2(path), isFunctionNotation(node) ? "" : ": ", print("value")];
+ }
- const canBreak = isBinaryish$5(rightNode) && !shouldInlineLogicalExpression$1(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$5(rightNode.test) && !shouldInlineLogicalExpression$1(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$3(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$3(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
- options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
+ case "ObjectTypeAnnotation":
+ return printObject$2(path, options, print);
- if (canBreak) {
- return group$k(indent$n(concat$t([line$i, printedRight])));
- }
+ case "ObjectTypeInternalSlot":
+ return [node.static ? "static " : "", "[[", print("id"), "]]", printOptionalToken$2(path), node.method ? "" : ": ", print("value")];
+ // Same as `RestElement`
- return concat$t([" ", printedRight]);
-}
+ case "ObjectTypeSpreadProperty":
+ return printRestSpread$1(path, options, print);
-var assignment = {
- printVariableDeclarator,
- printAssignmentExpression,
- printAssignment,
- printAssignmentRight
-};
+ case "QualifiedTypeIdentifier":
+ return [print("qualification"), ".", print("id")];
-const {
- isNextLineEmpty: isNextLineEmpty$7
-} = util;
-const {
- builders: {
- concat: concat$u,
- join: join$d,
- hardline: hardline$h
- }
-} = document;
-const {
- classChildNeedsASIProtection: classChildNeedsASIProtection$1,
- classPropMayCauseASIProblems: classPropMayCauseASIProblems$1,
- getLeftSidePathName: getLeftSidePathName$2,
- hasNakedLeftSide: hasNakedLeftSide$2,
- isJSXNode: isJSXNode$7,
- isLastStatement: isLastStatement$1,
- isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1
-} = utils$6;
-const {
- locEnd: locEnd$b
-} = loc;
-const {
- shouldPrintParamsWithoutParens: shouldPrintParamsWithoutParens$1
-} = _function;
-/** @typedef {import("../../document").Doc} Doc */
+ case "StringLiteralTypeAnnotation":
+ return printString$2(rawText$1(node), options);
-function printStatement({
- path,
- index,
- bodyNode,
- isClass
-}, options, print) {
- const node = path.getValue(); // Just in case the AST has been modified to contain falsy
- // "statements," it's safer simply to skip them.
+ case "NumberLiteralTypeAnnotation":
+ assert$1.strictEqual(typeof node.value, "number");
+ // fall through
- /* istanbul ignore if */
+ case "BigIntLiteralTypeAnnotation":
+ if (node.extra) {
+ return printNumber$2(node.extra.raw);
+ }
- if (!node) {
- return;
- } // Skip printing EmptyStatement nodes to avoid leaving stray
- // semicolons lying around.
+ return printNumber$2(node.raw);
+ case "TypeCastExpression":
+ {
+ return ["(", print("expression"), printTypeAnnotation$1(path, options, print), ")"];
+ }
- if (node.type === "EmptyStatement") {
- return;
- }
+ case "TypeParameterDeclaration":
+ case "TypeParameterInstantiation":
+ {
+ const printed = printTypeParameters$1(path, options, print, "params");
- const printed = print(path);
- const text = options.originalText;
- const 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.parser === "flow") {
+ const start = locStart$j(node);
+ const end = locEnd$i(node);
+ const commentStartIndex = options.originalText.lastIndexOf("/*", start);
+ const commentEndIndex = options.originalText.indexOf("*/", end);
- if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, path) && statementNeedsASIProtection(path, options)) {
- if (node.comments && node.comments.some(comment => comment.leading)) {
- parts.push(print(path, {
- needsSemi: true
- }));
- } else {
- parts.push(";", printed);
- }
- } else {
- parts.push(printed);
- }
+ if (commentStartIndex !== -1 && commentEndIndex !== -1) {
+ const comment = options.originalText.slice(commentStartIndex + 2, commentEndIndex).trim();
- if (!options.semi && isClass) {
- if (classPropMayCauseASIProblems$1(path)) {
- parts.push(";");
- } else if (node.type === "ClassProperty" || node.type === "FieldDefinition") {
- const nextChild = bodyNode.body[index + 1];
+ if (comment.startsWith("::") && !comment.includes("/*") && !comment.includes("*/")) {
+ return ["/*:: ", printed, " */"];
+ }
+ }
+ }
- if (classChildNeedsASIProtection$1(nextChild)) {
- parts.push(";");
+ return printed;
}
- }
- }
-
- if (isNextLineEmpty$7(text, node, locEnd$b) && !isLastStatement$1(path)) {
- parts.push(hardline$h);
- }
-
- return concat$u(parts);
-}
-
-function printStatementSequence(path, options, print) {
- const bodyNode = path.getNode();
- const isClass = bodyNode.type === "ClassBody";
- const printed = path.map((statementPath, index) => printStatement({
- path,
- index,
- bodyNode,
- isClass
- }, options, print)).filter(Boolean);
- return join$d(hardline$h, printed);
-}
-function statementNeedsASIProtection(path, options) {
- const node = path.getNode();
+ 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.
- if (node.type !== "ExpressionStatement") {
- return false;
- }
+ case "DeclaredPredicate":
+ return ["%checks(", print("value"), ")"];
- return path.call(childPath => expressionNeedsASIProtection(childPath, options), "expression");
-}
+ case "AnyTypeAnnotation":
+ return "any";
-function expressionNeedsASIProtection(path, options) {
- const node = path.getValue();
- const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens$1(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$7(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
+ case "BooleanTypeAnnotation":
+ return "boolean";
- if (maybeASIProblem) {
- return true;
- }
+ case "BigIntTypeAnnotation":
+ return "bigint";
- if (!hasNakedLeftSide$2(node)) {
- return false;
- }
+ case "NullLiteralTypeAnnotation":
+ return "null";
- return path.call(childPath => expressionNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
-}
+ case "NumberTypeAnnotation":
+ return "number";
-var statement = {
- printStatementSequence
-};
+ case "SymbolTypeAnnotation":
+ return "symbol";
-const {
- printDanglingComments: printDanglingComments$9
-} = comments;
-const {
- isNextLineEmpty: isNextLineEmpty$8
-} = util;
-const {
- builders: {
- concat: concat$v,
- hardline: hardline$i,
- indent: indent$o
- }
-} = document;
-const {
- hasDanglingComments: hasDanglingComments$6
-} = utils$6;
-const {
- locEnd: locEnd$c
-} = loc;
-const {
- printStatementSequence: printStatementSequence$1
-} = statement;
-/** @typedef {import("../../document").Doc} Doc */
+ case "StringTypeAnnotation":
+ return "string";
-function printBlock(path, options, print) {
- const n = path.getValue();
- const parts = [];
- const semi = options.semi ? ";" : "";
- const naked = path.call(bodyPath => {
- return printStatementSequence$1(bodyPath, options, print);
- }, "body");
+ case "VoidTypeAnnotation":
+ return "void";
- if (n.type === "StaticBlock") {
- parts.push("static ");
- }
+ case "ThisTypeAnnotation":
+ return "this";
+ // These types are unprintable because they serve as abstract
+ // supertypes for other (printable) types.
- const hasContent = n.body.some(node => node.type !== "EmptyStatement");
- const hasDirectives = n.directives && n.directives.length > 0;
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
+ 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
- if (!hasContent && !hasDirectives && !hasDanglingComments$6(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration" || parent.type === "TSDeclareFunction" || n.type === "StaticBlock")) {
- return concat$v([...parts, "{}"]);
+ case "Type":
+ /* istanbul ignore next */
+ throw new Error("unprintable type: " + JSON.stringify(node.type));
}
+}
- parts.push("{"); // Babel 6
-
- if (hasDirectives) {
- path.each(childPath => {
- parts.push(indent$o(concat$v([hardline$i, print(childPath), semi])));
+function printFlowDeclaration(path, printed) {
+ const parentExportDecl = getParentExportDeclaration(path);
- if (isNextLineEmpty$8(options.originalText, childPath.getValue(), locEnd$c)) {
- parts.push(hardline$i);
- }
- }, "directives");
- }
+ if (parentExportDecl) {
+ assert$1.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
+ return printed;
+ } // 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.
- if (hasContent) {
- parts.push(indent$o(concat$v([hardline$i, naked])));
- }
- parts.push(printDanglingComments$9(path, options));
- parts.push(hardline$i, "}");
- return concat$v(parts);
+ return ["declare ", printed];
}
-var block = {
- printBlock
+var flow = {
+ printFlow: printFlow$1
};
const {
- hasNewline: hasNewline$6
-} = util;
+ hasNewlineInRange: hasNewlineInRange$1
+} = util$8;
const {
- builders: {
- concat: concat$w,
- join: join$e,
- hardline: hardline$j
- }
-} = document;
+ isJsxNode: isJsxNode$1,
+ isBlockComment: isBlockComment$2,
+ getComments,
+ isCallExpression: isCallExpression$2,
+ isMemberExpression: isMemberExpression$2
+} = utils$5;
const {
- isLineComment: isLineComment$2,
- isBlockComment: isBlockComment$8
-} = utils$6;
+ locStart: locStart$i,
+ locEnd: locEnd$h
+} = loc$6;
const {
- locStart: locStart$7,
- locEnd: locEnd$d
-} = loc;
+ builders: {
+ line: line$g,
+ softline: softline$c,
+ group: group$g,
+ indent: indent$b,
+ align: align$2,
+ ifBreak: ifBreak$a,
+ dedent: dedent$3,
+ breakParent: breakParent$6
+ }
+} = require$$7$3;
+/**
+ * @typedef {import("../../document").Doc} Doc
+ * @typedef {import("../../common/ast-path")} AstPath
+ *
+ * @typedef {any} Options - Prettier options (TBD ...)
+ */
+// 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: ...,
+// }
+// }
+// }
-function printComment$1(commentPath, options) {
- const comment = commentPath.getValue();
+function conditionalExpressionChainContainsJsx(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 don't care about whether each node was the test, consequent, or alternate
+ // We are only checking if there's any JSXElements inside.
+ const conditionalExpressions = [node];
- if (isLineComment$2(comment)) {
- // Supports `//`, `#!`, ``
- return options.originalText.slice(locStart$7(comment), locEnd$d(comment)).trimEnd();
- }
+ for (let index = 0; index < conditionalExpressions.length; index++) {
+ const conditionalExpression = conditionalExpressions[index];
- if (isBlockComment$8(comment)) {
- if (isIndentableBlockComment(comment)) {
- const printed = printIndentableBlockComment(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
+ for (const property of ["test", "consequent", "alternate"]) {
+ const node = conditionalExpression[property];
- if (comment.trailing && !hasNewline$6(options.originalText, locStart$7(comment), {
- backwards: true
- })) {
- return concat$w([hardline$j, printed]);
+ if (isJsxNode$1(node)) {
+ return true;
}
- return printed;
+ if (node.type === "ConditionalExpression") {
+ conditionalExpressions.push(node);
+ }
}
-
- const commentEnd = locEnd$d(comment);
- const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
- return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
}
- /* istanbul ignore next */
-
- throw new Error("Not a comment: " + JSON.stringify(comment));
-}
-
-function isIndentableBlockComment(comment) {
- // If the comment has multiple lines and every line starts with a star
- // we can fix the indentation of each line. The stars in the `/*` and
- // `*/` delimiters are not included in the comment value, so add them
- // back first.
- const lines = `*${comment.value}*`.split("\n");
- return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
-}
-
-function printIndentableBlockComment(comment) {
- const lines = comment.value.split("\n");
- return concat$w(["/*", join$e(hardline$j, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
+ return false;
}
-var comment = {
- printComment: printComment$1
-};
-
-/** @typedef {import("../document").Doc} Doc */
-
-/** @type {import("assert")} */
-// TODO(azz): anything that imports from main shouldn't be in a `language-*` dir.
-
-
-const {
- hasNewline: hasNewline$7,
- hasNewlineInRange: hasNewlineInRange$6,
- getLast: getLast$9,
- printString: printString$2,
- printNumber: printNumber$2,
- isNextLineEmpty: isNextLineEmpty$9
-} = util;
-const {
- builders: {
- concat: concat$x,
- join: join$f,
- line: line$j,
- hardline: hardline$k,
- softline: softline$h,
- literalline: literalline$3,
- group: group$l,
- indent: indent$p,
- align: align$4,
- conditionalGroup: conditionalGroup$4,
- ifBreak: ifBreak$d
- },
- utils: {
- isEmpty: isEmpty$2
- }
-} = document;
-const {
- insertPragma: insertPragma$1
-} = pragma;
-const {
- printHtmlBinding: printHtmlBinding$1,
- isVueEventBindingExpression: isVueEventBindingExpression$1
-} = htmlBinding;
-const {
- getFunctionParameters: getFunctionParameters$6,
- getCallArguments: getCallArguments$3,
- getParentExportDeclaration: getParentExportDeclaration$2,
- getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1,
- hasDanglingComments: hasDanglingComments$7,
- hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$3,
- hasLeadingOwnLineComment: hasLeadingOwnLineComment$4,
- hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$2,
- hasNgSideEffect: hasNgSideEffect$1,
- hasPrettierIgnore: hasPrettierIgnore$1,
- hasTrailingComment: hasTrailingComment$6,
- isExportDeclaration: isExportDeclaration$1,
- isFunctionNotation: isFunctionNotation$1,
- isGetterOrSetter: isGetterOrSetter$1,
- isLiteral: isLiteral$2,
- isNgForOf: isNgForOf$1,
- isObjectType: isObjectType$3,
- isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$2,
- isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$2,
- isTSXFile: isTSXFile$1,
- isBlockComment: isBlockComment$9,
- needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$2,
- rawText: rawText$3,
- shouldPrintComma: shouldPrintComma$8
-} = utils$6;
-const {
- locStart: locStart$8,
- locEnd: locEnd$e
-} = loc;
-const {
- printOptionalToken: printOptionalToken$6,
- printBindExpressionCallee: printBindExpressionCallee$2,
- printTypeScriptModifiers: printTypeScriptModifiers$2,
- printDecorators: printDecorators$2,
- printFlowDeclaration: printFlowDeclaration$1,
- adjustClause: adjustClause$1
-} = misc;
-const {
- printImportDeclaration: printImportDeclaration$1,
- printExportDeclaration: printExportDeclaration$1,
- printExportAllDeclaration: printExportAllDeclaration$1,
- printModuleSpecifier: printModuleSpecifier$1
-} = module$3;
-const {
- printFunctionParameters: printFunctionParameters$2
-} = functionParameters;
-const {
- printTemplateLiteral: printTemplateLiteral$1
-} = templateLiteral;
-const {
- printArray: printArray$1,
- printArrayItems: printArrayItems$1
-} = array$3;
-const {
- printObject: printObject$1
-} = object;
-const {
- printTypeAnnotation: printTypeAnnotation$3,
- shouldHugType: shouldHugType$3
-} = typeAnnotation;
-const {
- printJsxElement: printJsxElement$1,
- printJsxAttribute: printJsxAttribute$1,
- printJsxOpeningElement: printJsxOpeningElement$1,
- printJsxClosingElement: printJsxClosingElement$1,
- printJsxOpeningClosingFragment: printJsxOpeningClosingFragment$1,
- printJsxExpressionContainer: printJsxExpressionContainer$1,
- printJsxEmptyExpression: printJsxEmptyExpression$1,
- printJsxSpreadAttribute: printJsxSpreadAttribute$1,
- printJsxSpreadChild
-} = jsx;
-const {
- printClass: printClass$1,
- printClassMethod: printClassMethod$1
-} = _class;
-const {
- printTypeParameters: printTypeParameters$1
-} = typeParameters;
-const {
- printPropertyKey: printPropertyKey$2
-} = property$1;
-const {
- printFunctionDeclaration: printFunctionDeclaration$1,
- printArrowFunctionExpression: printArrowFunctionExpression$1,
- printMethod: printMethod$2,
- printReturnAndThrowArgument: printReturnAndThrowArgument$1
-} = _function;
-const {
- printCallExpression: printCallExpression$1
-} = callExpression;
-const {
- printInterface: printInterface$1
-} = _interface;
-const {
- printVariableDeclarator: printVariableDeclarator$1,
- printAssignmentExpression: printAssignmentExpression$1,
- printAssignment: printAssignment$1,
- printAssignmentRight: printAssignmentRight$1
-} = assignment;
-const {
- printBinaryishExpression: printBinaryishExpression$1
-} = binaryish;
-const {
- printStatementSequence: printStatementSequence$2
-} = statement;
-const {
- printMemberExpression: printMemberExpression$1
-} = member;
-const {
- printBlock: printBlock$1
-} = block;
-const {
- printComment: printComment$2
-} = comment;
-
-function genericPrint(path, options, printPath, args) {
+function printTernaryTest(path, options, print) {
const node = path.getValue();
- let needsParens = false;
- const linesWithoutParens = printPathNoParens(path, options, printPath, args);
+ const isConditionalExpression = node.type === "ConditionalExpression";
+ const alternateNodePropertyName = isConditionalExpression ? "alternate" : "falseType";
+ const parent = path.getParentNode();
+ const printed = isConditionalExpression ? print("test") : [print("checkType"), " ", "extends", " ", print("extendsType")];
+ /**
+ * a
+ * ? b
+ * : multiline
+ * test
+ * node
+ * ^^ align(2)
+ * ? d
+ * : e
+ */
- if (!node || isEmpty$2(linesWithoutParens)) {
- return linesWithoutParens;
+ if (parent.type === node.type && parent[alternateNodePropertyName] === node) {
+ return align$2(2, printed);
}
- const parentExportDecl = getParentExportDeclaration$2(path);
- const decorators = [];
+ return printed;
+}
- if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "FieldDefinition" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
- // was written before the export, the export will be responsible
- // for printing the decorators.
- !(parentExportDecl && locStart$8(parentExportDecl, {
- ignoreDecorators: true
- }) > locStart$8(node.decorators[0]))) {
- const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$2(node, options);
- const separator = shouldBreak ? hardline$k : line$j;
- path.each(decoratorPath => {
- let decorator = decoratorPath.getValue();
-
- if (decorator.expression) {
- decorator = decorator.expression;
- } else {
- decorator = decorator.callee;
- }
+const ancestorNameMap = new Map([["AssignmentExpression", "right"], ["VariableDeclarator", "init"], ["ReturnStatement", "argument"], ["ThrowStatement", "argument"], ["UnaryExpression", "argument"], ["YieldExpression", "argument"]]);
- decorators.push(printPath(decoratorPath), separator);
- }, "decorators");
+function shouldExtraIndentForConditionalExpression(path) {
+ const node = path.getValue();
- if (parentExportDecl) {
- decorators.unshift(hardline$k);
- }
- } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export,
- // otherwise they are printed by the node.declaration
- locStart$8(node, {
- ignoreDecorators: true
- }) > locStart$8(node.declaration.decorators[0])) {
- // Export declarations are responsible for printing any decorators
- // that logically apply to node.declaration.
- path.each(decoratorPath => {
- const decorator = decoratorPath.getValue();
- const prefix = decorator.type === "Decorator" ? "" : "@";
- decorators.push(prefix, printPath(decoratorPath), hardline$k);
- }, "declaration", "decorators");
- } else {
- // Nodes with decorators can't have parentheses, so we can avoid
- // computing pathNeedsParens() except in this case.
- needsParens = needsParens_1(path, options);
+ if (node.type !== "ConditionalExpression") {
+ return false;
}
- const parts = [];
+ let parent;
+ let child = node;
- if (needsParens) {
- parts.unshift("(");
- }
+ for (let ancestorCount = 0; !parent; ancestorCount++) {
+ const node = path.getParentNode(ancestorCount);
- parts.push(linesWithoutParens);
+ if (isCallExpression$2(node) && node.callee === child || isMemberExpression$2(node) && node.object === child || node.type === "TSNonNullExpression" && node.expression === child) {
+ child = node;
+ continue;
+ } // Reached chain root
- if (needsParens) {
- const node = path.getValue();
- if (hasFlowShorthandAnnotationComment$3(node)) {
- parts.push(" /*");
- parts.push(node.trailingComments[0].value.trimStart());
- parts.push("*/");
- node.trailingComments[0].printed = true;
+ if (node.type === "NewExpression" && node.callee === child || node.type === "TSAsExpression" && node.expression === child) {
+ parent = path.getParentNode(ancestorCount + 1);
+ child = node;
+ } else {
+ parent = node;
}
+ } // Do not add indent to direct `ConditionalExpression`
- parts.push(")");
- }
- if (decorators.length > 0) {
- return group$l(concat$x(decorators.concat(parts)));
+ if (child === node) {
+ return false;
}
- return concat$x(parts);
+ return parent[ancestorNameMap.get(parent.type)] === child;
}
+/**
+ * The following is the shared logic for
+ * ternary operators, namely ConditionalExpression
+ * and TSConditionalType
+ * @param {AstPath} path - The path to the ConditionalExpression/TSConditionalType node.
+ * @param {Options} options - Prettier options
+ * @param {Function} print - Print function to call recursively
+ * @returns {Doc}
+ */
-function printPathNoParens(path, options, print, args) {
- const n = path.getValue();
- const semi = options.semi ? ";" : "";
- if (!n) {
- return "";
- }
+function printTernary$2(path, options, print) {
+ const node = path.getValue();
+ const isConditionalExpression = node.type === "ConditionalExpression";
+ const consequentNodePropertyName = isConditionalExpression ? "consequent" : "trueType";
+ const alternateNodePropertyName = isConditionalExpression ? "alternate" : "falseType";
+ const testNodePropertyNames = isConditionalExpression ? ["test"] : ["checkType", "extendsType"];
+ const consequentNode = node[consequentNodePropertyName];
+ const alternateNode = node[alternateNodePropertyName];
+ const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
+ // See `tests/format/jsx/conditional-expression.js` for more info.
- if (typeof n === "string") {
- return n;
- }
+ let jsxMode = false;
+ const parent = path.getParentNode();
+ const isParentTest = parent.type === node.type && testNodePropertyNames.some(prop => parent[prop] === node);
+ let forceNoIndent = parent.type === node.type && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
+ // ConditionalExpression parent. We'll use these to determine if we should
+ // print in JSX mode.
- const htmlBinding = printHtmlBinding$1(path, options, print);
+ let currentParent;
+ let previousParent;
+ let i = 0;
- if (htmlBinding) {
- return htmlBinding;
- }
- /** @type{Doc[]} */
+ do {
+ previousParent = currentParent || node;
+ currentParent = path.getParentNode(i);
+ i++;
+ } while (currentParent && currentParent.type === node.type && testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
+ const firstNonConditionalParent = currentParent || parent;
+ const lastConditionalParent = previousParent;
- let parts = [];
+ if (isConditionalExpression && (isJsxNode$1(node[testNodePropertyNames[0]]) || isJsxNode$1(consequentNode) || isJsxNode$1(alternateNode) || conditionalExpressionChainContainsJsx(lastConditionalParent))) {
+ jsxMode = true;
+ forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
+ // parens when using ?: within JSX, because the parens are analogous to
+ // curly braces in an if statement.
- switch (n.type) {
- case "JsExpressionRoot":
- return path.call(print, "node");
+ const wrap = doc => [ifBreak$a("("), indent$b([softline$c, doc]), softline$c, ifBreak$a(")")]; // The only things we don't wrap are:
+ // * Nested conditional expressions in alternates
+ // * null
+ // * undefined
- case "JsonRoot":
- return concat$x([path.call(print, "node"), hardline$k]);
- case "File":
- // Print @babel/parser's InterpreterDirective here so that
- // leading comments on the `Program` node get printed after the hashbang.
- if (n.program && n.program.interpreter) {
- parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program"));
- }
+ const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
- parts.push(path.call(print, "program"));
- return concat$x(parts);
+ parts.push(" ? ", isNil(consequentNode) ? print(consequentNodePropertyName) : wrap(print(consequentNodePropertyName)), " : ", alternateNode.type === node.type || isNil(alternateNode) ? print(alternateNodePropertyName) : wrap(print(alternateNodePropertyName)));
+ } else {
+ // normal mode
+ const part = [line$g, "? ", consequentNode.type === node.type ? ifBreak$a("", "(") : "", align$2(2, print(consequentNodePropertyName)), consequentNode.type === node.type ? ifBreak$a("", ")") : "", line$g, ": ", alternateNode.type === node.type ? print(alternateNodePropertyName) : align$2(2, print(alternateNodePropertyName))];
+ parts.push(parent.type !== node.type || parent[alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$3(indent$b(part)) : align$2(Math.max(0, options.tabWidth - 2), part));
+ } // We want a whole chain of ConditionalExpressions to all
+ // break if any of them break. That means we should only group around the
+ // outer-most ConditionalExpression.
- case "Program":
- {
- const hasContents = !n.body.every(({
- type
- }) => type === "EmptyStatement") || n.comments; // Babel 6
- if (n.directives) {
- const directivesCount = n.directives.length;
- path.each((childPath, index) => {
- parts.push(print(childPath), semi, hardline$k);
+ const comments = [...testNodePropertyNames.map(propertyName => getComments(node[propertyName])), getComments(consequentNode), getComments(alternateNode)].flat();
+ const shouldBreak = comments.some(comment => isBlockComment$2(comment) && hasNewlineInRange$1(options.originalText, locStart$i(comment), locEnd$h(comment)));
- if ((index < directivesCount - 1 || hasContents) && isNextLineEmpty$9(options.originalText, childPath.getValue(), locEnd$e)) {
- parts.push(hardline$k);
- }
- }, "directives");
- }
+ const maybeGroup = doc => parent === firstNonConditionalParent ? group$g(doc, {
+ shouldBreak
+ }) : shouldBreak ? [doc, breakParent$6] : doc; // Break the closing paren to keep the chain right after it:
+ // (a
+ // ? b
+ // : c
+ // ).call()
- parts.push(path.call(bodyPath => {
- return printStatementSequence$2(bodyPath, options, print);
- }, "body"));
- parts.push(comments.printDanglingComments(path, options,
- /* sameIndent */
- true)); // Only force a trailing newline if there were any contents.
- if (hasContents) {
- parts.push(hardline$k);
- }
+ const breakClosingParen = !jsxMode && (isMemberExpression$2(parent) || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
+ const shouldExtraIndent = shouldExtraIndentForConditionalExpression(path);
+ const result = maybeGroup([printTernaryTest(path, options, print), forceNoIndent ? parts : indent$b(parts), isConditionalExpression && breakClosingParen && !shouldExtraIndent ? softline$c : ""]);
+ return isParentTest || shouldExtraIndent ? group$g([indent$b([softline$c, result]), softline$c]) : result;
+}
- return concat$x(parts);
- }
- // Babel extension.
+var ternary = {
+ printTernary: printTernary$2
+};
- case "EmptyStatement":
- return "";
+const {
+ builders: {
+ hardline: hardline$k
+ }
+} = require$$7$3;
+const pathNeedsParens$1 = needsParens_1;
+const {
+ getLeftSidePathName,
+ hasNakedLeftSide,
+ isJsxNode,
+ isTheOnlyJsxElementInMarkdown: isTheOnlyJsxElementInMarkdown$1,
+ hasComment: hasComment$2,
+ CommentCheckFlags: CommentCheckFlags$2,
+ isNextLineEmpty: isNextLineEmpty$6
+} = utils$5;
+const {
+ shouldPrintParamsWithoutParens
+} = _function;
+/**
+ * @typedef {import("../../document").Doc} Doc
+ * @typedef {import("../../common/ast-path")} AstPath
+ */
- case "ExpressionStatement":
- // Detect Flow and TypeScript directives
- if (n.directive) {
- return concat$x([nodeStr(n.expression, options, true), semi]);
- }
+function printStatementSequence(path, options, print, property) {
+ const node = path.getValue();
+ const parts = [];
+ const isClassBody = node.type === "ClassBody";
+ const lastStatement = getLastStatement(node[property]);
+ path.each((path, index, statements) => {
+ const node = path.getValue(); // Skip printing EmptyStatement nodes to avoid leaving stray
+ // semicolons lying around.
- if (options.parser === "__vue_event_binding") {
- const parent = path.getParentNode();
+ if (node.type === "EmptyStatement") {
+ return;
+ }
- if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
- return concat$x([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
- }
- } // Do not append semicolon after the only JSX element in a program
+ const printed = print(); // 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 && !isClassBody && !isTheOnlyJsxElementInMarkdown$1(options, path) && statementNeedsASIProtection(path, options)) {
+ if (hasComment$2(node, CommentCheckFlags$2.Leading)) {
+ parts.push(print([], {
+ needsSemi: true
+ }));
+ } else {
+ parts.push(";", printed);
+ }
+ } else {
+ parts.push(printed);
+ }
+
+ if (!options.semi && isClassBody && isClassProperty(node) && // `ClassBody` don't allow `EmptyStatement`,
+ // so we can use `statements` to get next node
+ shouldPrintSemicolonAfterClassProperty(node, statements[index + 1])) {
+ parts.push(";");
+ }
+ if (node !== lastStatement) {
+ parts.push(hardline$k);
- return concat$x([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$2(options, path) ? "" : semi]);
- // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
+ if (isNextLineEmpty$6(node, options)) {
+ parts.push(hardline$k);
+ }
+ }
+ }, property);
+ return parts;
+}
- case "ParenthesizedExpression":
- {
- const shouldHug = !n.expression.comments;
+function getLastStatement(statements) {
+ for (let i = statements.length - 1; i >= 0; i--) {
+ const statement = statements[i];
- if (shouldHug) {
- return concat$x(["(", path.call(print, "expression"), ")"]);
- }
+ if (statement.type !== "EmptyStatement") {
+ return statement;
+ }
+ }
+}
- return group$l(concat$x(["(", indent$p(concat$x([softline$h, path.call(print, "expression")])), softline$h, ")"]));
- }
+function statementNeedsASIProtection(path, options) {
+ const node = path.getNode();
- case "AssignmentExpression":
- return printAssignmentExpression$1(path, options, print);
+ if (node.type !== "ExpressionStatement") {
+ return false;
+ }
- case "VariableDeclarator":
- return printVariableDeclarator$1(path, options, print);
+ return path.call(childPath => expressionNeedsASIProtection(childPath, options), "expression");
+}
- case "BinaryExpression":
- case "LogicalExpression":
- case "NGPipeExpression":
- return printBinaryishExpression$1(path, options, print);
+function expressionNeedsASIProtection(path, options) {
+ const node = path.getValue();
- case "AssignmentPattern":
- return concat$x([path.call(print, "left"), " = ", path.call(print, "right")]);
+ switch (node.type) {
+ case "ParenthesizedExpression":
+ case "TypeCastExpression":
+ case "ArrayExpression":
+ case "ArrayPattern":
+ case "TemplateLiteral":
+ case "TemplateElement":
+ case "RegExpLiteral":
+ return true;
- case "TSTypeAssertion":
+ case "ArrowFunctionExpression":
{
- const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
- const castGroup = group$l(concat$x(["<", indent$p(concat$x([softline$h, path.call(print, "typeAnnotation")])), softline$h, ">"]));
- const exprContents = concat$x([ifBreak$d("("), indent$p(concat$x([softline$h, path.call(print, "expression")])), softline$h, ifBreak$d(")")]);
-
- if (shouldBreakAfterCast) {
- return conditionalGroup$4([concat$x([castGroup, path.call(print, "expression")]), concat$x([castGroup, group$l(exprContents, {
- shouldBreak: true
- })]), concat$x([castGroup, path.call(print, "expression")])]);
+ if (!shouldPrintParamsWithoutParens(path, options)) {
+ return true;
}
- return group$l(concat$x([castGroup, path.call(print, "expression")]));
+ break;
}
- case "OptionalMemberExpression":
- case "MemberExpression":
+ case "UnaryExpression":
{
- return printMemberExpression$1(path, options, print);
- }
+ const {
+ prefix,
+ operator
+ } = node;
- case "MetaProperty":
- return concat$x([path.call(print, "meta"), ".", path.call(print, "property")]);
+ if (prefix && (operator === "+" || operator === "-")) {
+ return true;
+ }
- case "BindExpression":
- if (n.object) {
- parts.push(path.call(print, "object"));
+ break;
}
- parts.push(group$l(indent$p(concat$x([softline$h, printBindExpressionCallee$2(path, options, print)]))));
- return concat$x(parts);
-
- case "Identifier":
+ case "BindExpression":
{
- return concat$x([n.name, printOptionalToken$6(path), printTypeAnnotation$3(path, options, print)]);
- }
-
- case "V8IntrinsicIdentifier":
- return concat$x(["%", n.name]);
-
- case "SpreadElement":
- case "SpreadElementPattern":
- case "SpreadProperty":
- case "SpreadPropertyPattern":
- case "RestElement":
- case "ObjectTypeSpreadProperty":
- return concat$x(["...", path.call(print, "argument"), printTypeAnnotation$3(path, options, print)]);
-
- case "FunctionDeclaration":
- case "FunctionExpression":
- parts.push(printFunctionDeclaration$1(path, print, options, args && args.expandLastArg && getCallArguments$3(path.getParentNode()).length > 1));
+ if (!node.object) {
+ return true;
+ }
- if (!n.body) {
- parts.push(semi);
+ break;
}
- return concat$x(parts);
-
- case "ArrowFunctionExpression":
- return printArrowFunctionExpression$1(path, options, print, args);
-
- case "YieldExpression":
- parts.push("yield");
-
- if (n.delegate) {
- parts.push("*");
- }
+ case "Literal":
+ {
+ if (node.regex) {
+ return true;
+ }
- if (n.argument) {
- parts.push(" ", path.call(print, "argument"));
+ break;
}
- return concat$x(parts);
-
- case "AwaitExpression":
+ default:
{
- parts.push("await");
-
- if (n.argument) {
- parts.push(" ", path.call(print, "argument"));
+ if (isJsxNode(node)) {
+ return true;
}
+ }
+ }
- const parent = path.getParentNode();
-
- if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) {
- return group$l(concat$x([indent$p(concat$x([softline$h, concat$x(parts)])), softline$h]));
- }
+ if (pathNeedsParens$1(path, options)) {
+ return true;
+ }
- return concat$x(parts);
- }
+ if (!hasNakedLeftSide(node)) {
+ return false;
+ }
- case "TSExportAssignment":
- return concat$x(["export = ", path.call(print, "expression"), semi]);
+ return path.call(childPath => expressionNeedsASIProtection(childPath, options), ...getLeftSidePathName(path, node));
+}
- case "ExportDefaultDeclaration":
- case "ExportNamedDeclaration":
- case "DeclareExportDeclaration":
- return printExportDeclaration$1(path, options, print);
+function printBody$1(path, options, print) {
+ return printStatementSequence(path, options, print, "body");
+}
- case "ExportAllDeclaration":
- case "DeclareExportAllDeclaration":
- return printExportAllDeclaration$1(path, options, print);
+function printSwitchCaseConsequent$1(path, options, print) {
+ return printStatementSequence(path, options, print, "consequent");
+}
- case "ImportDeclaration":
- return printImportDeclaration$1(path, options, print);
+const isClassProperty = ({
+ type
+}) => type === "ClassProperty" || type === "PropertyDefinition" || type === "ClassPrivateProperty";
+/**
+ * @returns {boolean}
+ */
- case "ImportSpecifier":
- case "ExportSpecifier":
- case "ImportNamespaceSpecifier":
- case "ExportNamespaceSpecifier":
- case "ImportDefaultSpecifier":
- case "ExportDefaultSpecifier":
- return printModuleSpecifier$1(path, options, print);
- case "ImportAttribute":
- return concat$x([path.call(print, "key"), ": ", path.call(print, "value")]);
+function shouldPrintSemicolonAfterClassProperty(node, nextNode) {
+ const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
+ // so isn't properly tested yet.
- case "Import":
- return "import";
+ if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
+ return true;
+ }
- case "TSModuleBlock":
- case "BlockStatement":
- case "StaticBlock":
- return printBlock$1(path, options, print);
+ if (!nextNode) {
+ return false;
+ }
- case "ThrowStatement":
- case "ReturnStatement":
- return concat$x([n.type === "ReturnStatement" ? "return" : "throw", printReturnAndThrowArgument$1(path, options, print)]);
+ if (nextNode.static || nextNode.accessibility // TypeScript
+ ) {
+ return false;
+ }
- case "NewExpression":
- case "ImportExpression":
- case "OptionalCallExpression":
- case "CallExpression":
- return printCallExpression$1(path, options, print);
+ if (!nextNode.computed) {
+ const name = nextNode.key && nextNode.key.name;
- case "ObjectTypeInternalSlot":
- return concat$x([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken$6(path), n.method ? "" : ": ", path.call(print, "value")]);
+ if (name === "in" || name === "instanceof") {
+ return true;
+ }
+ } // Flow variance sigil +/- requires semi if there's no
+ // "declare" or "static" keyword before it.
- case "ObjectExpression":
- case "ObjectPattern":
- case "ObjectTypeAnnotation":
- case "TSInterfaceBody":
- case "TSTypeLiteral":
- case "RecordExpression":
- return printObject$1(path, options, print);
- // Babel 6
- case "ObjectProperty": // Non-standard AST node type.
+ if (isClassProperty(nextNode) && nextNode.variance && !nextNode.static && !nextNode.declare) {
+ return true;
+ }
- case "Property":
- if (n.method || n.kind === "get" || n.kind === "set") {
- return printMethod$2(path, options, print);
- }
+ switch (nextNode.type) {
+ case "ClassProperty":
+ case "PropertyDefinition":
+ case "TSAbstractPropertyDefinition":
+ return nextNode.computed;
- if (n.shorthand) {
- parts.push(path.call(print, "value"));
- } else {
- parts.push(printAssignment$1(n.key, printPropertyKey$2(path, options, print), ":", n.value, path.call(print, "value"), options));
- }
+ case "MethodDefinition": // Flow
- return concat$x(parts);
- // Babel 6
+ case "TSAbstractMethodDefinition": // TypeScript
case "ClassMethod":
case "ClassPrivateMethod":
- case "MethodDefinition":
- case "TSAbstractMethodDefinition":
- case "TSDeclareMethod":
- return printClassMethod$1(path, options, print);
-
- case "ObjectMethod":
- return printMethod$2(path, options, print);
-
- case "Decorator":
- return concat$x(["@", path.call(print, "expression"), path.call(print, "callee")]);
+ {
+ // Babel
+ const isAsync = nextNode.value ? nextNode.value.async : nextNode.async;
- case "ArrayExpression":
- case "ArrayPattern":
- case "TupleExpression":
- return printArray$1(path, options, print);
+ if (isAsync || nextNode.kind === "get" || nextNode.kind === "set") {
+ return false;
+ }
- case "SequenceExpression":
- {
- const parent = path.getParentNode(0);
+ const isGenerator = nextNode.value ? nextNode.value.generator : nextNode.generator;
- if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
- // For ExpressionStatements and for-loop heads, which are among
- // the few places a SequenceExpression appears unparenthesized, we want
- // to indent expressions after the first.
- const parts = [];
- path.each(p => {
- if (p.getName() === 0) {
- parts.push(print(p));
- } else {
- parts.push(",", indent$p(concat$x([line$j, print(p)])));
- }
- }, "expressions");
- return group$l(concat$x(parts));
+ if (nextNode.computed || isGenerator) {
+ return true;
}
- return group$l(concat$x([join$f(concat$x([",", line$j]), path.map(print, "expressions"))]));
+ return false;
}
- case "ThisExpression":
- return "this";
-
- case "Super":
- return "super";
+ case "TSIndexSignature":
+ return true;
+ }
+ /* istanbul ignore next */
- case "NullLiteral":
- // Babel 6 Literal split
- return "null";
- case "RegExpLiteral":
- // Babel 6 Literal split
- return printRegex(n);
+ return false;
+}
- case "NumericLiteral":
- // Babel 6 Literal split
- return printNumber$2(n.extra.raw);
+var statement = {
+ printBody: printBody$1,
+ printSwitchCaseConsequent: printSwitchCaseConsequent$1
+};
- case "DecimalLiteral":
- return printNumber$2(n.value) + "m";
+const {
+ printDanglingComments: printDanglingComments$2
+} = comments$4;
+const {
+ isNonEmptyArray: isNonEmptyArray$7
+} = util$8;
+const {
+ builders: {
+ hardline: hardline$j,
+ indent: indent$a
+ }
+} = require$$7$3;
+const {
+ hasComment: hasComment$1,
+ CommentCheckFlags: CommentCheckFlags$1,
+ isNextLineEmpty: isNextLineEmpty$5
+} = utils$5;
+const {
+ printHardlineAfterHeritage
+} = _class;
+const {
+ printBody
+} = statement;
+/** @typedef {import("../../document").Doc} Doc */
- case "BigIntLiteral":
- // babel: n.extra.raw, flow: n.bigint
- return (n.bigint || n.extra.raw).toLowerCase();
+function printBlock$4(path, options, print) {
+ const node = path.getValue();
+ const parts = [];
- case "BooleanLiteral": // Babel 6 Literal split
+ if (node.type === "StaticBlock") {
+ parts.push("static ");
+ }
- case "StringLiteral": // Babel 6 Literal split
+ if (node.type === "ClassBody" && isNonEmptyArray$7(node.body)) {
+ const parent = path.getParentNode();
+ parts.push(printHardlineAfterHeritage(parent));
+ }
- case "Literal":
- if (n.regex) {
- return printRegex(n.regex);
- } // typescript
+ parts.push("{");
+ const printed = printBlockBody$1(path, options, print);
+ if (printed) {
+ parts.push(indent$a([hardline$j, printed]), hardline$j);
+ } else {
+ const parent = path.getParentNode();
+ const parentParent = path.getParentNode(1);
- if (n.bigint) {
- return n.raw.toLowerCase();
- }
+ if (!(parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration" || parent.type === "TSDeclareFunction" || node.type === "StaticBlock" || node.type === "ClassBody")) {
+ parts.push(hardline$j);
+ }
+ }
- if (typeof n.value === "number") {
- return printNumber$2(n.raw);
- }
+ parts.push("}");
+ return parts;
+}
- if (typeof n.value !== "string") {
- return "" + n.value;
- }
+function printBlockBody$1(path, options, print) {
+ const node = path.getValue();
+ const nodeHasDirectives = isNonEmptyArray$7(node.directives);
+ const nodeHasBody = node.body.some(node => node.type !== "EmptyStatement");
+ const nodeHasComment = hasComment$1(node, CommentCheckFlags$1.Dangling);
- return nodeStr(n, options);
+ if (!nodeHasDirectives && !nodeHasBody && !nodeHasComment) {
+ return "";
+ }
- case "Directive":
- return path.call(print, "value");
- // Babel 6
+ const parts = []; // Babel 6
- case "DirectiveLiteral":
- return nodeStr(n, options);
+ if (nodeHasDirectives) {
+ path.each((childPath, index, directives) => {
+ parts.push(print());
- case "UnaryExpression":
- parts.push(n.operator);
+ if (index < directives.length - 1 || nodeHasBody || nodeHasComment) {
+ parts.push(hardline$j);
- if (/[a-z]$/.test(n.operator)) {
- parts.push(" ");
+ if (isNextLineEmpty$5(childPath.getValue(), options)) {
+ parts.push(hardline$j);
+ }
}
+ }, "directives");
+ }
- if (n.argument.comments && n.argument.comments.length > 0) {
- parts.push(group$l(concat$x(["(", indent$p(concat$x([softline$h, path.call(print, "argument")])), softline$h, ")"])));
- } else {
- parts.push(path.call(print, "argument"));
- }
+ if (nodeHasBody) {
+ parts.push(printBody(path, options, print));
+ }
- return concat$x(parts);
+ if (nodeHasComment) {
+ parts.push(printDanglingComments$2(path, options,
+ /* sameIndent */
+ true));
+ }
- case "UpdateExpression":
- parts.push(path.call(print, "argument"), n.operator);
+ if (node.type === "Program") {
+ const parent = path.getParentNode();
- if (n.prefix) {
- parts.reverse();
- }
+ if (!parent || parent.type !== "ModuleExpression") {
+ parts.push(hardline$j);
+ }
+ }
- return concat$x(parts);
+ return parts;
+}
- case "ConditionalExpression":
- return ternary(path, options, print, {
- beforeParts: () => [path.call(print, "test")],
- afterParts: breakClosingParen => [breakClosingParen ? softline$h : ""],
- shouldCheckJsx: true,
- conditionalNodeType: "ConditionalExpression",
- consequentNodePropertyName: "consequent",
- alternateNodePropertyName: "alternate",
- testNodePropertyNames: ["test"]
- });
+var block$1 = {
+ printBlock: printBlock$4,
+ printBlockBody: printBlockBody$1
+};
- case "VariableDeclaration":
- {
- const printed = path.map(childPath => {
- return print(childPath);
- }, "declarations"); // We generally want to terminate all variable declarations with a
- // semicolon, except when they in the () part of for loops.
+const {
+ printDanglingComments: printDanglingComments$1
+} = comments$4;
+const {
+ hasNewlineInRange
+} = util$8;
+const {
+ builders: {
+ join: join$e,
+ line: line$f,
+ hardline: hardline$i,
+ softline: softline$b,
+ group: group$f,
+ indent: indent$9,
+ conditionalGroup: conditionalGroup$1,
+ ifBreak: ifBreak$9
+ }
+} = require$$7$3;
+const {
+ isLiteral,
+ getTypeScriptMappedTypeModifier,
+ shouldPrintComma: shouldPrintComma$1,
+ isCallExpression: isCallExpression$1,
+ isMemberExpression: isMemberExpression$1
+} = utils$5;
+const {
+ locStart: locStart$h,
+ locEnd: locEnd$g
+} = loc$6;
+const {
+ printOptionalToken: printOptionalToken$1,
+ printTypeScriptModifiers
+} = misc$1;
+const {
+ printTernary: printTernary$1
+} = ternary;
+const {
+ printFunctionParameters,
+ shouldGroupFunctionParameters
+} = functionParameters;
+const {
+ printTemplateLiteral: printTemplateLiteral$1
+} = templateLiteral;
+const {
+ printArrayItems
+} = array;
+const {
+ printObject: printObject$1
+} = object$1;
+const {
+ printClassProperty: printClassProperty$1,
+ printClassMethod: printClassMethod$1
+} = _class;
+const {
+ printTypeParameter,
+ printTypeParameters
+} = typeParameters;
+const {
+ printPropertyKey
+} = property;
+const {
+ printFunction: printFunction$1,
+ printMethodInternal
+} = _function;
+const {
+ printInterface
+} = _interface;
+const {
+ printBlock: printBlock$3
+} = block$1;
+const {
+ printTypeAlias,
+ printIntersectionType,
+ printUnionType,
+ printFunctionType,
+ printTupleType,
+ printIndexedAccessType
+} = typeAnnotation;
- const parentNode = path.getParentNode();
- const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
- const hasValue = n.declarations.some(decl => decl.init);
- let firstVariable;
+function printTypescript$1(path, options, print) {
+ const node = path.getValue(); // TypeScript nodes always starts with `TS`
- if (printed.length === 1 && !n.declarations[0].comments) {
- firstVariable = printed[0];
- } else if (printed.length > 0) {
- // Indent first var to comply with eslint one-var rule
- firstVariable = indent$p(printed[0]);
- }
+ if (!node.type.startsWith("TS")) {
+ return;
+ }
- parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$x([" ", firstVariable]) : "", indent$p(concat$x(printed.slice(1).map(p => concat$x([",", hasValue && !isParentForLoop ? hardline$k : line$j, p]))))];
+ if (node.type.endsWith("Keyword")) {
+ return node.type.slice(2, -7).toLowerCase();
+ }
- if (!(isParentForLoop && parentNode.body !== n)) {
- parts.push(semi);
- }
+ const semi = options.semi ? ";" : "";
+ const parts = [];
- return group$l(concat$x(parts));
- }
+ switch (node.type) {
+ case "TSThisType":
+ return "this";
- case "TSTypeAliasDeclaration":
+ case "TSTypeAssertion":
{
- if (n.declare) {
- parts.push("declare ");
+ const shouldBreakAfterCast = !(node.expression.type === "ArrayExpression" || node.expression.type === "ObjectExpression");
+ const castGroup = group$f(["<", indent$9([softline$b, print("typeAnnotation")]), softline$b, ">"]);
+ const exprContents = [ifBreak$9("("), indent$9([softline$b, print("expression")]), softline$b, ifBreak$9(")")];
+
+ if (shouldBreakAfterCast) {
+ return conditionalGroup$1([[castGroup, print("expression")], [castGroup, group$f(exprContents, {
+ shouldBreak: true
+ })], [castGroup, print("expression")]]);
}
- const printed = printAssignmentRight$1(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
- parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
- return group$l(concat$x(parts));
+ return group$f([castGroup, print("expression")]);
}
- case "WithStatement":
- return group$l(concat$x(["with (", path.call(print, "object"), ")", adjustClause$1(n.body, path.call(print, "body"))]));
+ case "TSDeclareFunction":
+ return printFunction$1(path, print, options);
- case "IfStatement":
- {
- const con = adjustClause$1(n.consequent, path.call(print, "consequent"));
- const opening = group$l(concat$x(["if (", group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "test")])), softline$h])), ")", con]));
- parts.push(opening);
+ case "TSExportAssignment":
+ return ["export = ", print("expression"), semi];
- if (n.alternate) {
- const commentOnOwnLine = hasTrailingComment$6(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !isBlockComment$9(comment)) || needsHardlineAfterDanglingComment$2(n);
- const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
- parts.push(elseOnSameLine ? " " : hardline$k);
+ case "TSModuleBlock":
+ return printBlock$3(path, options, print);
- if (hasDanglingComments$7(n)) {
- parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$k : " ");
- }
+ case "TSInterfaceBody":
+ case "TSTypeLiteral":
+ return printObject$1(path, options, print);
- parts.push("else", group$l(adjustClause$1(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
- }
+ case "TSTypeAliasDeclaration":
+ return printTypeAlias(path, options, print);
- return concat$x(parts);
- }
+ case "TSQualifiedName":
+ return join$e(".", [print("left"), print("right")]);
- case "ForStatement":
- {
- const body = adjustClause$1(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
- // Any comment positioned between the for statement and the parentheses
- // is going to be printed before the statement.
+ case "TSAbstractMethodDefinition":
+ case "TSDeclareMethod":
+ return printClassMethod$1(path, options, print);
- const dangling = comments.printDanglingComments(path, options,
- /* sameLine */
- true);
- const printedComments = dangling ? concat$x([dangling, softline$h]) : "";
+ case "TSAbstractPropertyDefinition":
+ return printClassProperty$1(path, options, print);
- if (!n.init && !n.test && !n.update) {
- return concat$x([printedComments, group$l(concat$x(["for (;;)", body]))]);
- }
+ case "TSInterfaceHeritage":
+ case "TSExpressionWithTypeArguments":
+ // Babel AST
+ parts.push(print("expression"));
- return concat$x([printedComments, group$l(concat$x(["for (", group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "init"), ";", line$j, path.call(print, "test"), ";", line$j, path.call(print, "update")])), softline$h])), ")", body]))]);
+ if (node.typeParameters) {
+ parts.push(print("typeParameters"));
}
- case "WhileStatement":
- return group$l(concat$x(["while (", group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "test")])), softline$h])), ")", adjustClause$1(n.body, path.call(print, "body"))]));
+ return parts;
- case "ForInStatement":
- return group$l(concat$x(["for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause$1(n.body, path.call(print, "body"))]));
+ case "TSTemplateLiteralType":
+ return printTemplateLiteral$1(path, print, options);
- case "ForOfStatement":
- return group$l(concat$x(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause$1(n.body, path.call(print, "body"))]));
+ case "TSNamedTupleMember":
+ return [print("label"), node.optional ? "?" : "", ": ", print("elementType")];
- case "DoWhileStatement":
+ case "TSRestType":
+ return ["...", print("typeAnnotation")];
+
+ case "TSOptionalType":
+ return [print("typeAnnotation"), "?"];
+
+ case "TSInterfaceDeclaration":
+ return printInterface(path, options, print);
+
+ case "TSClassImplements":
+ return [print("expression"), print("typeParameters")];
+
+ case "TSTypeParameterDeclaration":
+ case "TSTypeParameterInstantiation":
+ return printTypeParameters(path, options, print, "params");
+
+ case "TSTypeParameter":
+ return printTypeParameter(path, options, print);
+
+ case "TSAsExpression":
{
- const clause = adjustClause$1(n.body, path.call(print, "body"));
- const doBody = group$l(concat$x(["do", clause]));
- parts = [doBody];
+ parts.push(print("expression"), " as ", print("typeAnnotation"));
+ const parent = path.getParentNode();
- if (n.body.type === "BlockStatement") {
- parts.push(" ");
- } else {
- parts.push(hardline$k);
+ if (isCallExpression$1(parent) && parent.callee === node || isMemberExpression$1(parent) && parent.object === node) {
+ return group$f([indent$9([softline$b, ...parts]), softline$b]);
}
- parts.push("while (");
- parts.push(group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "test")])), softline$h])), ")", semi);
- return concat$x(parts);
+ return parts;
}
- case "DoExpression":
- return concat$x(["do ", path.call(print, "body")]);
+ case "TSArrayType":
+ return [print("elementType"), "[]"];
- case "BreakStatement":
- parts.push("break");
+ case "TSPropertySignature":
+ {
+ if (node.readonly) {
+ parts.push("readonly ");
+ }
- if (n.label) {
- parts.push(" ", path.call(print, "label"));
- }
+ parts.push(printPropertyKey(path, options, print), printOptionalToken$1(path));
- parts.push(semi);
- return concat$x(parts);
+ if (node.typeAnnotation) {
+ parts.push(": ", print("typeAnnotation"));
+ } // This isn't valid semantically, but it's in the AST so we can print it.
- case "ContinueStatement":
- parts.push("continue");
- if (n.label) {
- parts.push(" ", path.call(print, "label"));
+ if (node.initializer) {
+ parts.push(" = ", print("initializer"));
+ }
+
+ return parts;
}
- parts.push(semi);
- return concat$x(parts);
+ case "TSParameterProperty":
+ if (node.accessibility) {
+ parts.push(node.accessibility + " ");
+ }
- case "LabeledStatement":
- if (n.body.type === "EmptyStatement") {
- return concat$x([path.call(print, "label"), ":;"]);
+ if (node.export) {
+ parts.push("export ");
}
- return concat$x([path.call(print, "label"), ": ", path.call(print, "body")]);
+ if (node.static) {
+ parts.push("static ");
+ }
- case "TryStatement":
- return concat$x(["try ", path.call(print, "block"), n.handler ? concat$x([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$x([" finally ", path.call(print, "finalizer")]) : ""]);
+ if (node.override) {
+ parts.push("override ");
+ }
- case "CatchClause":
- if (n.param) {
- const hasComments = n.param.comments && n.param.comments.some(comment => !isBlockComment$9(comment) || comment.leading && hasNewline$7(options.originalText, locEnd$e(comment)) || comment.trailing && hasNewline$7(options.originalText, locStart$8(comment), {
- backwards: true
- }));
- const param = path.call(print, "param");
- return concat$x(["catch ", hasComments ? concat$x(["(", indent$p(concat$x([softline$h, param])), softline$h, ") "]) : concat$x(["(", param, ") "]), path.call(print, "body")]);
+ if (node.readonly) {
+ parts.push("readonly ");
}
- return concat$x(["catch ", path.call(print, "body")]);
- // Note: ignoring n.lexical because it has no printing consequences.
+ parts.push(print("parameter"));
+ return parts;
- case "SwitchStatement":
- return concat$x([group$l(concat$x(["switch (", indent$p(concat$x([softline$h, path.call(print, "discriminant")])), softline$h, ")"])), " {", n.cases.length > 0 ? indent$p(concat$x([hardline$k, join$f(hardline$k, path.map(casePath => {
- const caseNode = casePath.getValue();
- return concat$x([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$9(options.originalText, caseNode, locEnd$e) ? hardline$k : ""]);
- }, "cases"))])) : "", hardline$k, "}"]);
+ case "TSTypeQuery":
+ return ["typeof ", print("exprName")];
- case "SwitchCase":
+ case "TSIndexSignature":
{
- if (n.test) {
- parts.push("case ", path.call(print, "test"), ":");
- } else {
- parts.push("default:");
- }
+ const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
+ // using them, it makes sense to have a trailing comma. But if you
+ // aren't, this is more like a computed property name than an array.
+ // So we leave off the trailing comma when there's just one parameter.
- const consequent = n.consequent.filter(node => node.type !== "EmptyStatement");
+ const trailingComma = node.parameters.length > 1 ? ifBreak$9(shouldPrintComma$1(options) ? "," : "") : "";
+ const parametersGroup = group$f([indent$9([softline$b, join$e([", ", softline$b], path.map(print, "parameters"))]), trailingComma, softline$b]);
+ return [node.export ? "export " : "", node.accessibility ? [node.accessibility, " "] : "", node.static ? "static " : "", node.readonly ? "readonly " : "", node.declare ? "declare " : "", "[", node.parameters ? parametersGroup : "", node.typeAnnotation ? "]: " : "]", node.typeAnnotation ? print("typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""];
+ }
- if (consequent.length > 0) {
- const cons = path.call(consequentPath => {
- return printStatementSequence$2(consequentPath, options, print);
- }, "consequent");
- parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$x([" ", cons]) : indent$p(concat$x([hardline$k, cons])));
- }
+ case "TSTypePredicate":
+ return [node.asserts ? "asserts " : "", print("parameterName"), node.typeAnnotation ? [" is ", print("typeAnnotation")] : ""];
- return concat$x(parts);
- }
- // JSX extensions below.
+ case "TSNonNullExpression":
+ return [print("expression"), "!"];
- case "DebuggerStatement":
- return concat$x(["debugger", semi]);
+ case "TSImportType":
+ return [!node.isTypeOf ? "" : "typeof ", "import(", print(node.parameter ? "parameter" : "argument"), ")", !node.qualifier ? "" : [".", print("qualifier")], printTypeParameters(path, options, print, "typeParameters")];
- case "JSXAttribute":
- return printJsxAttribute$1(path, options, print);
+ case "TSLiteralType":
+ return print("literal");
- case "JSXIdentifier":
- return "" + n.name;
+ case "TSIndexedAccessType":
+ return printIndexedAccessType(path, options, print);
- case "JSXNamespacedName":
- return join$f(":", [path.call(print, "namespace"), path.call(print, "name")]);
+ case "TSConstructSignatureDeclaration":
+ case "TSCallSignatureDeclaration":
+ case "TSConstructorType":
+ {
+ if (node.type === "TSConstructorType" && node.abstract) {
+ parts.push("abstract ");
+ }
- case "JSXMemberExpression":
- return join$f(".", [path.call(print, "object"), path.call(print, "property")]);
+ if (node.type !== "TSCallSignatureDeclaration") {
+ parts.push("new ");
+ }
- case "TSQualifiedName":
- return join$f(".", [path.call(print, "left"), path.call(print, "right")]);
+ parts.push(group$f(printFunctionParameters(path, print, options,
+ /* expandArg */
+ false,
+ /* printTypeParams */
+ true)));
- case "JSXSpreadAttribute":
- return printJsxSpreadAttribute$1(path, options, print);
+ if (node.returnType || node.typeAnnotation) {
+ const isType = node.type === "TSConstructorType";
+ parts.push(isType ? " => " : ": ", print("returnType"), print("typeAnnotation"));
+ }
- case "JSXSpreadChild":
- return printJsxSpreadChild(path, options, print);
+ return parts;
+ }
- case "JSXExpressionContainer":
- return printJsxExpressionContainer$1(path, options, print);
+ case "TSTypeOperator":
+ return [node.operator, " ", print("typeAnnotation")];
- case "JSXFragment":
- case "JSXElement":
- return printJsxElement$1(path, options, print);
+ case "TSMappedType":
+ {
+ const shouldBreak = hasNewlineInRange(options.originalText, locStart$h(node), locEnd$g(node));
+ return group$f(["{", indent$9([options.bracketSpacing ? line$f : softline$b, node.readonly ? [getTypeScriptMappedTypeModifier(node.readonly, "readonly"), " "] : "", printTypeScriptModifiers(path, options, print), print("typeParameter"), node.optional ? getTypeScriptMappedTypeModifier(node.optional, "?") : "", node.typeAnnotation ? ": " : "", print("typeAnnotation"), ifBreak$9(semi)]), printDanglingComments$1(path, options,
+ /* sameIndent */
+ true), options.bracketSpacing ? line$f : softline$b, "}"], {
+ shouldBreak
+ });
+ }
- case "JSXOpeningElement":
- return printJsxOpeningElement$1(path, options, print);
+ case "TSMethodSignature":
+ {
+ const kind = node.kind && node.kind !== "method" ? `${node.kind} ` : "";
+ parts.push(node.accessibility ? [node.accessibility, " "] : "", kind, node.export ? "export " : "", node.static ? "static " : "", node.readonly ? "readonly " : "", // "abstract" and "declare" are supported by only "babel-ts"
+ // https://github.com/prettier/prettier/issues/9760
+ node.abstract ? "abstract " : "", node.declare ? "declare " : "", node.computed ? "[" : "", print("key"), node.computed ? "]" : "", printOptionalToken$1(path));
+ const parametersDoc = printFunctionParameters(path, print, options,
+ /* expandArg */
+ false,
+ /* printTypeParams */
+ true);
+ const returnTypePropertyName = node.returnType ? "returnType" : "typeAnnotation";
+ const returnTypeNode = node[returnTypePropertyName];
+ const returnTypeDoc = returnTypeNode ? print(returnTypePropertyName) : "";
+ const shouldGroupParameters = shouldGroupFunctionParameters(node, returnTypeDoc);
+ parts.push(shouldGroupParameters ? group$f(parametersDoc) : parametersDoc);
- case "JSXClosingElement":
- return printJsxClosingElement$1(path, options, print);
+ if (returnTypeNode) {
+ parts.push(": ", group$f(returnTypeDoc));
+ }
- case "JSXOpeningFragment":
- case "JSXClosingFragment":
- return printJsxOpeningClosingFragment$1(path, options
- /*, print*/
- );
+ return group$f(parts);
+ }
- case "JSXText":
- /* istanbul ignore next */
- throw new Error("JSXTest should be handled by JSXElement");
+ case "TSNamespaceExportDeclaration":
+ parts.push("export as namespace ", print("id"));
- case "JSXEmptyExpression":
- return printJsxEmptyExpression$1(path, options
- /*, print*/
- );
+ if (options.semi) {
+ parts.push(";");
+ }
- case "ClassBody":
- if (!n.comments && n.body.length === 0) {
- return "{}";
+ return group$f(parts);
+
+ case "TSEnumDeclaration":
+ if (node.declare) {
+ parts.push("declare ");
}
- return concat$x(["{", n.body.length > 0 ? indent$p(concat$x([hardline$k, path.call(bodyPath => {
- return printStatementSequence$2(bodyPath, options, print);
- }, "body")])) : comments.printDanglingComments(path, options), hardline$k, "}"]);
+ if (node.modifiers) {
+ parts.push(printTypeScriptModifiers(path, options, print));
+ }
- case "ClassProperty":
- case "FieldDefinition":
- case "TSAbstractClassProperty":
- case "ClassPrivateProperty":
- {
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators$2(path, options, print));
- }
+ if (node.const) {
+ parts.push("const ");
+ }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
+ parts.push("enum ", print("id"), " ");
- if (n.declare) {
- parts.push("declare ");
- }
+ if (node.members.length === 0) {
+ parts.push(group$f(["{", printDanglingComments$1(path, options), softline$b, "}"]));
+ } else {
+ parts.push(group$f(["{", indent$9([hardline$i, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""]), printDanglingComments$1(path, options,
+ /* sameIndent */
+ true), hardline$i, "}"]));
+ }
- if (n.static) {
- parts.push("static ");
- }
+ return parts;
- if (n.type === "TSAbstractClassProperty" || n.abstract) {
- parts.push("abstract ");
- }
+ case "TSEnumMember":
+ parts.push(print("id"));
- if (n.readonly) {
- parts.push("readonly ");
- }
+ if (node.initializer) {
+ parts.push(" = ", print("initializer"));
+ }
- if (n.variance) {
- parts.push(path.call(print, "variance"));
- }
+ return parts;
- parts.push(printPropertyKey$2(path, options, print), printOptionalToken$6(path), printTypeAnnotation$3(path, options, print));
+ case "TSImportEqualsDeclaration":
+ if (node.isExport) {
+ parts.push("export ");
+ }
- if (n.value) {
- parts.push(" =", printAssignmentRight$1(n.key, n.value, path.call(print, "value"), options));
- }
+ parts.push("import ");
- parts.push(semi);
- return group$l(concat$x(parts));
+ if (node.importKind && node.importKind !== "value") {
+ parts.push(node.importKind, " ");
}
- case "ClassDeclaration":
- case "ClassExpression":
- if (n.declare) {
- parts.push("declare ");
+ parts.push(print("id"), " = ", print("moduleReference"));
+
+ if (options.semi) {
+ parts.push(";");
}
- parts.push(printClass$1(path, options, print));
- return concat$x(parts);
+ return group$f(parts);
- case "TSInterfaceHeritage":
- case "TSExpressionWithTypeArguments":
- // Babel AST
- parts.push(path.call(print, "expression"));
+ case "TSExternalModuleReference":
+ return ["require(", print("expression"), ")"];
- if (n.typeParameters) {
- parts.push(path.call(print, "typeParameters"));
- }
+ case "TSModuleDeclaration":
+ {
+ const parent = path.getParentNode();
+ const isExternalModule = isLiteral(node.id);
+ const parentIsDeclaration = parent.type === "TSModuleDeclaration";
+ const bodyIsDeclaration = node.body && node.body.type === "TSModuleDeclaration";
- return concat$x(parts);
+ if (parentIsDeclaration) {
+ parts.push(".");
+ } else {
+ if (node.declare) {
+ parts.push("declare ");
+ }
- case "TemplateElement":
- return join$f(literalline$3, n.value.raw.split(/\r?\n/g));
+ parts.push(printTypeScriptModifiers(path, options, print));
+ const textBetweenNodeAndItsId = options.originalText.slice(locStart$h(node), locStart$h(node.id)); // Global declaration looks like this:
+ // (declare)? global { ... }
- case "TSTemplateLiteralType":
- case "TemplateLiteral":
- {
- return printTemplateLiteral$1(path, print, options);
- }
+ const isGlobalDeclaration = node.id.type === "Identifier" && node.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
- case "TaggedTemplateExpression":
- return concat$x([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
- // These types are unprintable because they serve as abstract
- // supertypes for other (printable) types.
+ if (!isGlobalDeclaration) {
+ parts.push(isExternalModule || /(?:^|\s)module(?:\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
+ }
+ }
- 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
+ parts.push(print("id"));
- 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.
+ if (bodyIsDeclaration) {
+ parts.push(print("body"));
+ } else if (node.body) {
+ parts.push(" ", group$f(print("body")));
+ } else {
+ parts.push(semi);
+ }
- case "TypeAnnotation":
- case "TSTypeAnnotation":
- if (n.typeAnnotation) {
- return path.call(print, "typeAnnotation");
+ return parts;
}
- /* istanbul ignore next */
+ case "TSConditionalType":
+ return printTernary$1(path, options, print);
- return "";
+ case "TSInferType":
+ return ["infer", " ", print("typeParameter")];
- case "TSNamedTupleMember":
- return concat$x([path.call(print, "label"), n.optional ? "?" : "", ": ", path.call(print, "elementType")]);
+ case "TSIntersectionType":
+ return printIntersectionType(path, options, print);
+
+ case "TSUnionType":
+ return printUnionType(path, options, print);
+
+ case "TSFunctionType":
+ return printFunctionType(path, options, print);
case "TSTupleType":
- case "TupleTypeAnnotation":
- {
- const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
- const hasRest = n[typesField].length > 0 && getLast$9(n[typesField]).type === "TSRestType";
- return group$l(concat$x(["[", indent$p(concat$x([softline$h, printArrayItems$1(path, options, typesField, print)])), ifBreak$d(shouldPrintComma$8(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), softline$h, "]"]));
- }
+ return printTupleType(path, options, print);
- case "ExistsTypeAnnotation":
- return "*";
+ case "TSTypeReference":
+ return [print("typeName"), printTypeParameters(path, options, print, "typeParameters")];
- case "EmptyTypeAnnotation":
- return "empty";
+ case "TSTypeAnnotation":
+ return print("typeAnnotation");
- case "MixedTypeAnnotation":
- return "mixed";
+ case "TSEmptyBodyFunctionExpression":
+ return printMethodInternal(path, options, print);
+ // These are not valid TypeScript. Printing them just for the sake of error recovery.
- case "ArrayTypeAnnotation":
- return concat$x([path.call(print, "elementType"), "[]"]);
+ case "TSJSDocAllType":
+ return "*";
- case "BooleanLiteralTypeAnnotation":
- return "" + n.value;
+ case "TSJSDocUnknownType":
+ return "?";
- case "DeclareClass":
- return printFlowDeclaration$1(path, printClass$1(path, options, print));
+ case "TSJSDocNullableType":
+ return ["?", print("typeAnnotation")];
- case "TSDeclareFunction":
- // For TypeScript the TSDeclareFunction node shares the AST
- // structure with FunctionDeclaration
- return concat$x([n.declare ? "declare " : "", printFunctionDeclaration$1(path, print, options), semi]);
+ case "TSJSDocNonNullableType":
+ return ["!", print("typeAnnotation")];
- case "DeclareFunction":
- return printFlowDeclaration$1(path, concat$x(["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]));
+ default:
+ /* istanbul ignore next */
+ throw new Error(`Unknown TypeScript node type: ${JSON.stringify(node.type)}.`);
+ }
+}
- case "DeclareModule":
- return printFlowDeclaration$1(path, concat$x(["module ", path.call(print, "id"), " ", path.call(print, "body")]));
+var typescript = {
+ printTypescript: printTypescript$1
+};
- case "DeclareModuleExports":
- return printFlowDeclaration$1(path, concat$x(["module.exports", ": ", path.call(print, "typeAnnotation"), semi]));
+const {
+ hasNewline: hasNewline$2
+} = util$8;
+const {
+ builders: {
+ join: join$d,
+ hardline: hardline$h
+ },
+ utils: {
+ replaceTextEndOfLine: replaceTextEndOfLine$a
+ }
+} = require$$7$3;
+const {
+ isLineComment: isLineComment$1,
+ isBlockComment: isBlockComment$1
+} = utils$5;
+const {
+ locStart: locStart$g,
+ locEnd: locEnd$f
+} = loc$6;
- case "DeclareVariable":
- return printFlowDeclaration$1(path, concat$x(["var ", path.call(print, "id"), semi]));
+function printComment$2(commentPath, options) {
+ const comment = commentPath.getValue();
- case "DeclareOpaqueType":
- case "OpaqueType":
- {
- parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
+ if (isLineComment$1(comment)) {
+ // Supports `//`, `#!`, ``
+ return options.originalText.slice(locStart$g(comment), locEnd$f(comment)).trimEnd();
+ }
- if (n.supertype) {
- parts.push(": ", path.call(print, "supertype"));
- }
+ if (isBlockComment$1(comment)) {
+ if (isIndentableBlockComment(comment)) {
+ const printed = printIndentableBlockComment(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 (n.impltype) {
- parts.push(" = ", path.call(print, "impltype"));
- }
+ if (comment.trailing && !hasNewline$2(options.originalText, locStart$g(comment), {
+ backwards: true
+ })) {
+ return [hardline$h, printed];
+ }
- parts.push(semi);
+ return printed;
+ }
- if (n.type === "DeclareOpaqueType") {
- return printFlowDeclaration$1(path, concat$x(parts));
- }
+ const commentEnd = locEnd$f(comment);
+ const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
+ return ["/*", replaceTextEndOfLine$a(comment.value), isInsideFlowComment ? "*-/" : "*/"];
+ }
+ /* istanbul ignore next */
- return concat$x(parts);
- }
- case "EnumDeclaration":
- return concat$x(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
+ throw new Error("Not a comment: " + JSON.stringify(comment));
+}
- case "EnumBooleanBody":
- case "EnumNumberBody":
- case "EnumStringBody":
- case "EnumSymbolBody":
- {
- if (n.type === "EnumSymbolBody" || n.explicitType) {
- let type = null;
+function isIndentableBlockComment(comment) {
+ // If the comment has multiple lines and every line starts with a star
+ // we can fix the indentation of each line. The stars in the `/*` and
+ // `*/` delimiters are not included in the comment value, so add them
+ // back first.
+ const lines = `*${comment.value}*`.split("\n");
+ return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
+}
- switch (n.type) {
- case "EnumBooleanBody":
- type = "boolean";
- break;
+function printIndentableBlockComment(comment) {
+ const lines = comment.value.split("\n");
+ return ["/*", join$d(hardline$h, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"];
+}
- case "EnumNumberBody":
- type = "number";
- break;
+var comment = {
+ printComment: printComment$2
+};
- case "EnumStringBody":
- type = "string";
- break;
+const {
+ printString: printString$1,
+ printNumber: printNumber$1
+} = util$8;
- case "EnumSymbolBody":
- type = "symbol";
- break;
- }
+function printLiteral$1(path, options
+/*, print*/
+) {
+ const node = path.getNode();
- parts.push("of ", type, " ");
- }
+ switch (node.type) {
+ case "RegExpLiteral":
+ // Babel 6 Literal split
+ return printRegex(node);
- if (n.members.length === 0 && !n.hasUnknownMembers) {
- parts.push(group$l(concat$x(["{", comments.printDanglingComments(path, options), softline$h, "}"])));
- } else {
- const members = n.members.length ? [hardline$k, printArrayItems$1(path, options, "members", print), n.hasUnknownMembers || shouldPrintComma$8(options) ? "," : ""] : [];
- parts.push(group$l(concat$x(["{", indent$p(concat$x([...members, ...(n.hasUnknownMembers ? [hardline$k, "..."] : [])])), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), hardline$k, "}"])));
- }
+ case "BigIntLiteral":
+ // babel: node.extra.raw, flow: node.bigint
+ return printBigInt(node.bigint || node.extra.raw);
- return concat$x(parts);
- }
+ case "NumericLiteral":
+ // Babel 6 Literal split
+ return printNumber$1(node.extra.raw);
- case "EnumBooleanMember":
- case "EnumNumberMember":
- case "EnumStringMember":
- return concat$x([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
+ case "StringLiteral":
+ // Babel 6 Literal split
+ return printString$1(node.extra.raw, options);
- case "EnumDefaultedMember":
- return path.call(print, "id");
+ case "NullLiteral":
+ // Babel 6 Literal split
+ return "null";
- case "FunctionTypeAnnotation":
- case "TSFunctionType":
- {
- // FunctionTypeAnnotation is ambiguous:
- // declare function foo(a: B): void; OR
- // var A: (a: B) => void;
- const parent = path.getParentNode(0);
- const parentParent = path.getParentNode(1);
- const parentParentParent = path.getParentNode(2);
- let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !parent.variance && !parent.optional && locStart$8(parent) === locStart$8(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
- let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.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 :(
+ case "BooleanLiteral":
+ // Babel 6 Literal split
+ return String(node.value);
- const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
+ case "DecimalLiteral":
+ return printNumber$1(node.value) + "m";
- if (isObjectTypePropertyAFunction$2(parent)) {
- isArrowFunctionTypeAnnotation = true;
- needsColon = true;
+ case "Literal":
+ {
+ if (node.regex) {
+ return printRegex(node.regex);
}
- if (needsParens) {
- parts.push("(");
+ if (node.bigint) {
+ return printBigInt(node.raw);
}
- parts.push(printFunctionParameters$2(path, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
- // needs to be added separately.
+ if (node.decimal) {
+ return printNumber$1(node.decimal) + "m";
+ }
+
+ const {
+ value
+ } = node;
- if (n.returnType || n.predicate || n.typeAnnotation) {
- parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
+ if (typeof value === "number") {
+ return printNumber$1(node.raw);
}
- if (needsParens) {
- parts.push(")");
+ if (typeof value === "string") {
+ return printString$1(node.raw, options);
}
- return group$l(concat$x(parts));
+ return String(value);
}
+ }
+}
- case "TSRestType":
- return concat$x(["...", path.call(print, "typeAnnotation")]);
+function printBigInt(raw) {
+ return raw.toLowerCase();
+}
- case "TSOptionalType":
- return concat$x([path.call(print, "typeAnnotation"), "?"]);
+function printRegex({
+ pattern,
+ flags
+}) {
+ flags = [...flags].sort().join("");
+ return `/${pattern}/${flags}`;
+}
- case "FunctionTypeParam":
- {
- const name = n.name ? path.call(print, "name") : path.getParentNode().this === n ? "this" : "";
- return concat$x([name, printOptionalToken$6(path), name ? ": " : "", path.call(print, "typeAnnotation")]);
- }
+var literal = {
+ printLiteral: printLiteral$1
+};
- case "DeclareInterface":
- case "InterfaceDeclaration":
- case "InterfaceTypeAnnotation":
- case "TSInterfaceDeclaration":
- return printInterface$1(path, options, print);
+/** @typedef {import("../document").Doc} Doc */
+// TODO(azz): anything that imports from main shouldn't be in a `language-*` dir.
- case "ClassImplements":
- case "InterfaceExtends":
- return concat$x([path.call(print, "id"), path.call(print, "typeParameters")]);
- case "TSClassImplements":
- return concat$x([path.call(print, "expression"), path.call(print, "typeParameters")]);
+const {
+ printDanglingComments
+} = comments$4;
+const {
+ hasNewline: hasNewline$1
+} = util$8;
+const {
+ builders: {
+ join: join$c,
+ line: line$e,
+ hardline: hardline$g,
+ softline: softline$a,
+ group: group$e,
+ indent: indent$8
+ },
+ utils: {
+ replaceTextEndOfLine: replaceTextEndOfLine$9
+ }
+} = require$$7$3;
+const embed$9 = embed_1$4;
+const clean$b = clean_1$4;
+const {
+ insertPragma: insertPragma$9
+} = pragma$5;
+const handleComments = comments;
+const pathNeedsParens = needsParens_1;
+const preprocess$7 = printPreprocess$3;
+const {
+ hasFlowShorthandAnnotationComment,
+ hasComment,
+ CommentCheckFlags,
+ isTheOnlyJsxElementInMarkdown,
+ isBlockComment,
+ isLineComment,
+ isNextLineEmpty: isNextLineEmpty$4,
+ needsHardlineAfterDanglingComment,
+ rawText,
+ hasIgnoreComment,
+ isCallExpression,
+ isMemberExpression
+} = utils$5;
+const {
+ locStart: locStart$f,
+ locEnd: locEnd$e
+} = loc$6;
+const {
+ printHtmlBinding,
+ isVueEventBindingExpression: isVueEventBindingExpression$2
+} = htmlBinding;
+const {
+ printAngular
+} = angular;
+const {
+ printJsx,
+ hasJsxIgnoreComment
+} = jsx;
+const {
+ printFlow
+} = flow;
+const {
+ printTypescript
+} = typescript;
+const {
+ printOptionalToken,
+ printBindExpressionCallee,
+ printTypeAnnotation,
+ adjustClause,
+ printRestSpread
+} = misc$1;
+const {
+ printImportDeclaration,
+ printExportDeclaration,
+ printExportAllDeclaration,
+ printModuleSpecifier
+} = module$1;
+const {
+ printTernary
+} = ternary;
+const {
+ printTemplateLiteral
+} = templateLiteral;
+const {
+ printArray
+} = array;
+const {
+ printObject
+} = object$1;
+const {
+ printClass,
+ printClassMethod,
+ printClassProperty
+} = _class;
+const {
+ printProperty
+} = property;
+const {
+ printFunction,
+ printArrowFunction,
+ printMethod,
+ printReturnStatement,
+ printThrowStatement
+} = _function;
+const {
+ printCallExpression
+} = callExpression;
+const {
+ printVariableDeclarator,
+ printAssignmentExpression
+} = assignment;
+const {
+ printBinaryishExpression
+} = binaryish;
+const {
+ printSwitchCaseConsequent
+} = statement;
+const {
+ printMemberExpression
+} = member;
+const {
+ printBlock: printBlock$2,
+ printBlockBody
+} = block$1;
+const {
+ printComment: printComment$1
+} = comment;
+const {
+ printLiteral
+} = literal;
+const {
+ printDecorators
+} = decorators;
- case "TSIntersectionType":
- case "IntersectionTypeAnnotation":
- {
- const types = path.map(print, "types");
- const result = [];
- let wasIndented = false;
-
- for (let i = 0; i < types.length; ++i) {
- if (i === 0) {
- result.push(types[i]);
- } else if (isObjectType$3(n.types[i - 1]) && isObjectType$3(n.types[i])) {
- // If both are objects, don't indent
- result.push(concat$x([" & ", wasIndented ? indent$p(types[i]) : types[i]]));
- } else if (!isObjectType$3(n.types[i - 1]) && !isObjectType$3(n.types[i])) {
- // If no object is involved, go to the next line if it breaks
- result.push(indent$p(concat$x([" &", line$j, types[i]])));
- } else {
- // If you go from object to non-object or vis-versa, then inline it
- if (i > 1) {
- wasIndented = true;
- }
+function genericPrint$6(path, options, print, args) {
+ const printed = printPathNoParens(path, options, print, args);
- result.push(" & ", i > 1 ? indent$p(types[i]) : types[i]);
- }
- }
+ if (!printed) {
+ return "";
+ }
- return group$l(concat$x(result));
- }
+ const node = path.getValue();
+ const {
+ type
+ } = node; // Their decorators are handled themselves, and they can't have parentheses
- case "TSUnionType":
- case "UnionTypeAnnotation":
- {
- // single-line variation
- // A | B | C
- // multi-line variation
- // | A
- // | B
- // | C
- const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
-
- const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name && path.getParentNode(1).this !== parent) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$4(options.originalText, n)); // {
- // a: string
- // } | null | void
- // should be inlined and not be printed in the multi-line variant
-
- const shouldHug = shouldHugType$3(n); // We want to align the children but without its comment, so it looks like
- // | child1
- // // comment
- // | child2
-
- const printed = path.map(typePath => {
- let printedType = typePath.call(print);
-
- if (!shouldHug) {
- printedType = align$4(2, printedType);
- }
+ if (type === "ClassMethod" || type === "ClassPrivateMethod" || type === "ClassProperty" || type === "PropertyDefinition" || type === "TSAbstractPropertyDefinition" || type === "ClassPrivateProperty" || type === "MethodDefinition" || type === "TSAbstractMethodDefinition" || type === "TSDeclareMethod") {
+ return printed;
+ }
- return comments.printComments(typePath, () => printedType, options);
- }, "types");
+ const printedDecorators = printDecorators(path, options, print); // Nodes with decorators can't have parentheses and don't need leading semicolons
- if (shouldHug) {
- return join$f(" | ", printed);
- }
+ if (printedDecorators) {
+ return group$e([...printedDecorators, printed]);
+ }
- const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$4(options.originalText, n);
- const code = concat$x([ifBreak$d(concat$x([shouldAddStartLine ? line$j : "", "| "])), join$f(concat$x([line$j, "| "]), printed)]);
+ const needsParens = pathNeedsParens(path, options);
- if (needsParens_1(path, options)) {
- return group$l(concat$x([indent$p(code), softline$h]));
- }
+ if (!needsParens) {
+ return args && args.needsSemi ? [";", printed] : printed;
+ }
- if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
- return group$l(concat$x([indent$p(concat$x([ifBreak$d(concat$x(["(", softline$h])), code])), softline$h, ifBreak$d(")")]));
- }
+ const parts = [args && args.needsSemi ? ";(" : "(", printed];
- return group$l(shouldIndent ? indent$p(code) : code);
- }
+ if (hasFlowShorthandAnnotationComment(node)) {
+ const [comment] = node.trailingComments;
+ parts.push(" /*", comment.value.trimStart(), "*/");
+ comment.printed = true;
+ }
- case "NullableTypeAnnotation":
- return concat$x(["?", path.call(print, "typeAnnotation")]);
+ parts.push(")");
+ return parts;
+}
- case "Variance":
- {
- const {
- kind
- } = n;
- assert__default['default'].ok(kind === "plus" || kind === "minus");
- return kind === "plus" ? "+" : "-";
- }
+function printPathNoParens(path, options, print, args) {
+ const node = path.getValue();
+ const semi = options.semi ? ";" : "";
- case "ObjectTypeCallProperty":
- if (n.static) {
- parts.push("static ");
- }
+ if (!node) {
+ return "";
+ }
- parts.push(path.call(print, "value"));
- return concat$x(parts);
+ if (typeof node === "string") {
+ return node;
+ }
- case "ObjectTypeIndexer":
- {
- return concat$x([n.variance ? path.call(print, "variance") : "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
- }
+ for (const printer of [printLiteral, printHtmlBinding, printAngular, printJsx, printFlow, printTypescript]) {
+ const printed = printer(path, options, print);
- case "ObjectTypeProperty":
- {
- let modifier = "";
+ if (typeof printed !== "undefined") {
+ return printed;
+ }
+ }
+ /** @type{Doc[]} */
- if (n.proto) {
- modifier = "proto ";
- } else if (n.static) {
- modifier = "static ";
- }
- return concat$x([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", n.variance ? path.call(print, "variance") : "", printPropertyKey$2(path, options, print), printOptionalToken$6(path), isFunctionNotation$1(n) ? "" : ": ", path.call(print, "value")]);
+ let parts = [];
+
+ switch (node.type) {
+ case "JsExpressionRoot":
+ return print("node");
+
+ case "JsonRoot":
+ return [print("node"), hardline$g];
+
+ case "File":
+ // Print @babel/parser's InterpreterDirective here so that
+ // leading comments on the `Program` node get printed after the hashbang.
+ if (node.program && node.program.interpreter) {
+ parts.push(print(["program", "interpreter"]));
}
- case "QualifiedTypeIdentifier":
- return concat$x([path.call(print, "qualification"), ".", path.call(print, "id")]);
+ parts.push(print("program"));
+ return parts;
- case "StringLiteralTypeAnnotation":
- return nodeStr(n, options);
+ case "Program":
+ return printBlockBody(path, options, print);
+ // Babel extension.
- case "NumberLiteralTypeAnnotation":
- assert__default['default'].strictEqual(typeof n.value, "number");
- // fall through
+ case "EmptyStatement":
+ return "";
- case "BigIntLiteralTypeAnnotation":
- if (n.extra != null) {
- return printNumber$2(n.extra.raw);
+ case "ExpressionStatement":
+ // Detect Flow and TypeScript directives
+ if (node.directive) {
+ return [printDirective(node.expression, options), semi];
}
- return printNumber$2(n.raw);
+ if (options.parser === "__vue_event_binding") {
+ const parent = path.getParentNode();
- case "DeclareTypeAlias":
- case "TypeAlias":
- {
- if (n.type === "DeclareTypeAlias" || n.declare) {
- parts.push("declare ");
+ if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === node) {
+ return [print("expression"), isVueEventBindingExpression$2(node.expression) ? ";" : ""];
}
+ } // Do not append semicolon after the only JSX element in a program
- const printed = printAssignmentRight$1(n.id, n.right, path.call(print, "right"), options);
- parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
- return group$l(concat$x(parts));
- }
- case "TypeCastExpression":
- {
- return concat$x(["(", path.call(print, "expression"), printTypeAnnotation$3(path, options, print), ")"]);
- }
+ return [print("expression"), isTheOnlyJsxElementInMarkdown(options, path) ? "" : semi];
+ // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
- case "TypeParameterDeclaration":
- case "TypeParameterInstantiation":
+ case "ParenthesizedExpression":
{
- const printed = printTypeParameters$1(path, options, print, "params");
-
- if (options.parser === "flow") {
- const start = locStart$8(n);
- const end = locEnd$e(n);
- const commentStartIndex = options.originalText.lastIndexOf("/*", start);
- const commentEndIndex = options.originalText.indexOf("*/", end);
-
- if (commentStartIndex !== -1 && commentEndIndex !== -1) {
- const comment = options.originalText.slice(commentStartIndex + 2, commentEndIndex).trim();
+ const shouldHug = !hasComment(node.expression) && (node.expression.type === "ObjectExpression" || node.expression.type === "ArrayExpression");
- if (comment.startsWith("::") && !comment.includes("/*") && !comment.includes("*/")) {
- return concat$x(["/*:: ", printed, " */"]);
- }
- }
+ if (shouldHug) {
+ return ["(", print("expression"), ")"];
}
- return printed;
+ return group$e(["(", indent$8([softline$a, print("expression")]), softline$a, ")"]);
}
- case "TSTypeParameterDeclaration":
- case "TSTypeParameterInstantiation":
- return printTypeParameters$1(path, options, print, "params");
+ case "AssignmentExpression":
+ return printAssignmentExpression(path, options, print);
- case "TSTypeParameter":
- case "TypeParameter":
- {
- const parent = path.getParentNode();
+ case "VariableDeclarator":
+ return printVariableDeclarator(path, options, print);
- if (parent.type === "TSMappedType") {
- parts.push("[", path.call(print, "name"));
+ case "BinaryExpression":
+ case "LogicalExpression":
+ return printBinaryishExpression(path, options, print);
- if (n.constraint) {
- parts.push(" in ", path.call(print, "constraint"));
- }
+ case "AssignmentPattern":
+ return [print("left"), " = ", print("right")];
- if (parent.nameType) {
- parts.push(" as ", path.callParent(path => {
- return path.call(print, "nameType");
- }));
- }
+ case "OptionalMemberExpression":
+ case "MemberExpression":
+ {
+ return printMemberExpression(path, options, print);
+ }
- parts.push("]");
- return concat$x(parts);
- }
+ case "MetaProperty":
+ return [print("meta"), ".", print("property")];
- if (n.variance) {
- parts.push(path.call(print, "variance"));
- }
+ case "BindExpression":
+ if (node.object) {
+ parts.push(print("object"));
+ }
- parts.push(path.call(print, "name"));
+ parts.push(group$e(indent$8([softline$a, printBindExpressionCallee(path, options, print)])));
+ return parts;
- if (n.bound) {
- parts.push(": ");
- parts.push(path.call(print, "bound"));
- }
+ case "Identifier":
+ {
+ return [node.name, printOptionalToken(path), printTypeAnnotation(path, options, print)];
+ }
- if (n.constraint) {
- parts.push(" extends ", path.call(print, "constraint"));
- }
+ case "V8IntrinsicIdentifier":
+ return ["%", node.name];
- if (n.default) {
- parts.push(" = ", path.call(print, "default"));
- } // Keep comma if the file extension is .tsx and
- // has one type parameter that isn't extend with any types.
- // Because, otherwise formatted result will be invalid as tsx.
+ case "SpreadElement":
+ case "SpreadElementPattern":
+ case "SpreadProperty":
+ case "SpreadPropertyPattern":
+ case "RestElement":
+ return printRestSpread(path, options, print);
+ case "FunctionDeclaration":
+ case "FunctionExpression":
+ return printFunction(path, print, options, args);
- const grandParent = path.getNode(2);
+ case "ArrowFunctionExpression":
+ return printArrowFunction(path, options, print, args);
- if (getFunctionParameters$6(parent).length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
- parts.push(",");
- }
+ case "YieldExpression":
+ parts.push("yield");
- return concat$x(parts);
+ if (node.delegate) {
+ parts.push("*");
}
- case "TypeofTypeAnnotation":
- return concat$x(["typeof ", path.call(print, "argument")]);
-
- 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$x(["%checks(", path.call(print, "value"), ")"]);
-
- case "TSAbstractKeyword":
- return "abstract";
+ if (node.argument) {
+ parts.push(" ", print("argument"));
+ }
- case "AnyTypeAnnotation":
- case "TSAnyKeyword":
- return "any";
+ return parts;
- case "TSAsyncKeyword":
- return "async";
+ case "AwaitExpression":
+ {
+ parts.push("await");
- case "BooleanTypeAnnotation":
- case "TSBooleanKeyword":
- return "boolean";
+ if (node.argument) {
+ parts.push(" ", print("argument"));
+ const parent = path.getParentNode();
- case "BigIntTypeAnnotation":
- case "TSBigIntKeyword":
- return "bigint";
+ if (isCallExpression(parent) && parent.callee === node || isMemberExpression(parent) && parent.object === node) {
+ parts = [indent$8([softline$a, ...parts]), softline$a];
+ const parentAwaitOrBlock = path.findAncestor(node => node.type === "AwaitExpression" || node.type === "BlockStatement");
- case "TSConstKeyword":
- return "const";
+ if (!parentAwaitOrBlock || parentAwaitOrBlock.type !== "AwaitExpression") {
+ return group$e(parts);
+ }
+ }
+ }
- case "TSDeclareKeyword":
- return "declare";
+ return parts;
+ }
- case "TSExportKeyword":
- return "export";
+ case "ExportDefaultDeclaration":
+ case "ExportNamedDeclaration":
+ return printExportDeclaration(path, options, print);
- case "NullLiteralTypeAnnotation":
- case "TSNullKeyword":
- return "null";
+ case "ExportAllDeclaration":
+ return printExportAllDeclaration(path, options, print);
- case "TSNeverKeyword":
- return "never";
+ case "ImportDeclaration":
+ return printImportDeclaration(path, options, print);
- case "NumberTypeAnnotation":
- case "TSNumberKeyword":
- return "number";
+ case "ImportSpecifier":
+ case "ExportSpecifier":
+ case "ImportNamespaceSpecifier":
+ case "ExportNamespaceSpecifier":
+ case "ImportDefaultSpecifier":
+ case "ExportDefaultSpecifier":
+ return printModuleSpecifier(path, options, print);
- case "TSObjectKeyword":
- return "object";
+ case "ImportAttribute":
+ return [print("key"), ": ", print("value")];
- case "TSProtectedKeyword":
- return "protected";
+ case "Import":
+ return "import";
- case "TSPrivateKeyword":
- return "private";
+ case "BlockStatement":
+ case "StaticBlock":
+ case "ClassBody":
+ return printBlock$2(path, options, print);
- case "TSPublicKeyword":
- return "public";
+ case "ThrowStatement":
+ return printThrowStatement(path, options, print);
- case "TSReadonlyKeyword":
- return "readonly";
+ case "ReturnStatement":
+ return printReturnStatement(path, options, print);
- case "SymbolTypeAnnotation":
- case "TSSymbolKeyword":
- return "symbol";
+ case "NewExpression":
+ case "ImportExpression":
+ case "OptionalCallExpression":
+ case "CallExpression":
+ return printCallExpression(path, options, print);
- case "TSStaticKeyword":
- return "static";
+ case "ObjectExpression":
+ case "ObjectPattern":
+ case "RecordExpression":
+ return printObject(path, options, print);
+ // Babel 6
- case "StringTypeAnnotation":
- case "TSStringKeyword":
- return "string";
+ case "ObjectProperty": // Non-standard AST node type.
- case "TSUndefinedKeyword":
- return "undefined";
+ case "Property":
+ if (node.method || node.kind === "get" || node.kind === "set") {
+ return printMethod(path, options, print);
+ }
- case "TSUnknownKeyword":
- return "unknown";
+ return printProperty(path, options, print);
- case "VoidTypeAnnotation":
- case "TSVoidKeyword":
- return "void";
+ case "ObjectMethod":
+ return printMethod(path, options, print);
- case "TSAsExpression":
- return concat$x([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
+ case "Decorator":
+ return ["@", print("expression")];
- case "TSArrayType":
- return concat$x([path.call(print, "elementType"), "[]"]);
+ case "ArrayExpression":
+ case "ArrayPattern":
+ case "TupleExpression":
+ return printArray(path, options, print);
- case "TSPropertySignature":
+ case "SequenceExpression":
{
- if (n.export) {
- parts.push("export ");
- }
+ const parent = path.getParentNode(0);
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
+ if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
+ // For ExpressionStatements and for-loop heads, which are among
+ // the few places a SequenceExpression appears unparenthesized, we want
+ // to indent expressions after the first.
+ const parts = [];
+ path.each((expressionPath, index) => {
+ if (index === 0) {
+ parts.push(print());
+ } else {
+ parts.push(",", indent$8([line$e, print()]));
+ }
+ }, "expressions");
+ return group$e(parts);
}
- if (n.static) {
- parts.push("static ");
- }
+ return group$e(join$c([",", line$e], path.map(print, "expressions")));
+ }
- if (n.readonly) {
- parts.push("readonly ");
- }
+ case "ThisExpression":
+ return "this";
- parts.push(printPropertyKey$2(path, options, print), printOptionalToken$6(path));
+ case "Super":
+ return "super";
- if (n.typeAnnotation) {
- parts.push(": ");
- parts.push(path.call(print, "typeAnnotation"));
- } // This isn't valid semantically, but it's in the AST so we can print it.
+ case "Directive":
+ return [print("value"), semi];
+ // Babel 6
+ case "DirectiveLiteral":
+ return printDirective(node, options);
- if (n.initializer) {
- parts.push(" = ", path.call(print, "initializer"));
- }
+ case "UnaryExpression":
+ parts.push(node.operator);
- return concat$x(parts);
+ if (/[a-z]$/.test(node.operator)) {
+ parts.push(" ");
}
- case "TSParameterProperty":
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
+ if (hasComment(node.argument)) {
+ parts.push(group$e(["(", indent$8([softline$a, print("argument")]), softline$a, ")"]));
+ } else {
+ parts.push(print("argument"));
}
- if (n.export) {
- parts.push("export ");
- }
+ return parts;
- if (n.static) {
- parts.push("static ");
- }
+ case "UpdateExpression":
+ parts.push(print("argument"), node.operator);
- if (n.readonly) {
- parts.push("readonly ");
+ if (node.prefix) {
+ parts.reverse();
}
- parts.push(path.call(print, "parameter"));
- return concat$x(parts);
-
- case "GenericTypeAnnotation":
- case "TSTypeReference":
- return concat$x([path.call(print, n.type === "TSTypeReference" ? "typeName" : "id"), printTypeParameters$1(path, options, print, "typeParameters")]);
+ return parts;
- case "TSTypeQuery":
- return concat$x(["typeof ", path.call(print, "exprName")]);
+ case "ConditionalExpression":
+ return printTernary(path, options, print);
- case "TSIndexSignature":
+ case "VariableDeclaration":
{
- const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
- // using them, it makes sense to have a trailing comma. But if you
- // aren't, this is more like a computed property name than an array.
- // So we leave off the trailing comma when there's just one parameter.
-
- const trailingComma = n.parameters.length > 1 ? ifBreak$d(shouldPrintComma$8(options) ? "," : "") : "";
- const parametersGroup = group$l(concat$x([indent$p(concat$x([softline$h, join$f(concat$x([", ", softline$h]), path.map(print, "parameters"))])), trailingComma, softline$h]));
- return concat$x([n.export ? "export " : "", n.accessibility ? concat$x([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.declare ? "declare " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
- }
+ const printed = path.map(print, "declarations"); // We generally want to terminate all variable declarations with a
+ // semicolon, except when they in the () part of for loops.
- case "TSTypePredicate":
- return concat$x([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$x([" is ", path.call(print, "typeAnnotation")]) : ""]);
+ const parentNode = path.getParentNode();
+ const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
+ const hasValue = node.declarations.some(decl => decl.init);
+ let firstVariable;
- case "TSNonNullExpression":
- return concat$x([path.call(print, "expression"), "!"]);
+ if (printed.length === 1 && !hasComment(node.declarations[0])) {
+ firstVariable = printed[0];
+ } else if (printed.length > 0) {
+ // Indent first var to comply with eslint one-var rule
+ firstVariable = indent$8(printed[0]);
+ }
- case "ThisTypeAnnotation":
- case "TSThisType":
- return "this";
+ parts = [node.declare ? "declare " : "", node.kind, firstVariable ? [" ", firstVariable] : "", indent$8(printed.slice(1).map(p => [",", hasValue && !isParentForLoop ? hardline$g : line$e, p]))];
- case "TSImportType":
- return concat$x([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$x([".", path.call(print, "qualifier")]), printTypeParameters$1(path, options, print, "typeParameters")]);
+ if (!(isParentForLoop && parentNode.body !== node)) {
+ parts.push(semi);
+ }
- case "TSLiteralType":
- return path.call(print, "literal");
+ return group$e(parts);
+ }
- case "TSIndexedAccessType":
- return concat$x([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
+ case "WithStatement":
+ return group$e(["with (", print("object"), ")", adjustClause(node.body, print("body"))]);
- case "TSConstructSignatureDeclaration":
- case "TSCallSignatureDeclaration":
- case "TSConstructorType":
+ case "IfStatement":
{
- if (n.type !== "TSCallSignatureDeclaration") {
- parts.push("new ");
- }
+ const con = adjustClause(node.consequent, print("consequent"));
+ const opening = group$e(["if (", group$e([indent$8([softline$a, print("test")]), softline$a]), ")", con]);
+ parts.push(opening);
- parts.push(group$l(printFunctionParameters$2(path, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true)));
+ if (node.alternate) {
+ const commentOnOwnLine = hasComment(node.consequent, CommentCheckFlags.Trailing | CommentCheckFlags.Line) || needsHardlineAfterDanglingComment(node);
+ const elseOnSameLine = node.consequent.type === "BlockStatement" && !commentOnOwnLine;
+ parts.push(elseOnSameLine ? " " : hardline$g);
+
+ if (hasComment(node, CommentCheckFlags.Dangling)) {
+ parts.push(printDanglingComments(path, options, true), commentOnOwnLine ? hardline$g : " ");
+ }
- if (n.returnType || n.typeAnnotation) {
- const isType = n.type === "TSConstructorType";
- parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
+ parts.push("else", group$e(adjustClause(node.alternate, print("alternate"), node.alternate.type === "IfStatement")));
}
- return concat$x(parts);
+ return parts;
}
- case "TSTypeOperator":
- return concat$x([n.operator, " ", path.call(print, "typeAnnotation")]);
-
- case "TSMappedType":
+ case "ForStatement":
{
- const shouldBreak = hasNewlineInRange$6(options.originalText, locStart$8(n), locEnd$e(n));
- return group$l(concat$x(["{", indent$p(concat$x([options.bracketSpacing ? line$j : softline$h, n.readonly ? concat$x([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers$2(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$d(semi, "")])), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), options.bracketSpacing ? line$j : softline$h, "}"]), {
- shouldBreak
- });
- }
+ const body = adjustClause(node.body, print("body")); // We want to keep dangling comments above the loop to stay consistent.
+ // Any comment positioned between the for statement and the parentheses
+ // is going to be printed before the statement.
- case "TSMethodSignature":
- parts.push(n.accessibility ? concat$x([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken$6(path), printFunctionParameters$2(path, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true));
+ const dangling = printDanglingComments(path, options,
+ /* sameLine */
+ true);
+ const printedComments = dangling ? [dangling, softline$a] : "";
+
+ if (!node.init && !node.test && !node.update) {
+ return [printedComments, group$e(["for (;;)", body])];
+ }
- if (n.returnType || n.typeAnnotation) {
- parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
+ return [printedComments, group$e(["for (", group$e([indent$8([softline$a, print("init"), ";", line$e, print("test"), ";", line$e, print("update")]), softline$a]), ")", body])];
}
- return group$l(concat$x(parts));
+ case "WhileStatement":
+ return group$e(["while (", group$e([indent$8([softline$a, print("test")]), softline$a]), ")", adjustClause(node.body, print("body"))]);
- case "TSNamespaceExportDeclaration":
- parts.push("export as namespace ", path.call(print, "id"));
+ case "ForInStatement":
+ return group$e(["for (", print("left"), " in ", print("right"), ")", adjustClause(node.body, print("body"))]);
- if (options.semi) {
- parts.push(";");
- }
+ case "ForOfStatement":
+ return group$e(["for", node.await ? " await" : "", " (", print("left"), " of ", print("right"), ")", adjustClause(node.body, print("body"))]);
- return group$l(concat$x(parts));
+ case "DoWhileStatement":
+ {
+ const clause = adjustClause(node.body, print("body"));
+ const doBody = group$e(["do", clause]);
+ parts = [doBody];
- case "TSEnumDeclaration":
- if (n.declare) {
- parts.push("declare ");
- }
+ if (node.body.type === "BlockStatement") {
+ parts.push(" ");
+ } else {
+ parts.push(hardline$g);
+ }
- if (n.modifiers) {
- parts.push(printTypeScriptModifiers$2(path, options, print));
+ parts.push("while (", group$e([indent$8([softline$a, print("test")]), softline$a]), ")", semi);
+ return parts;
}
- if (n.const) {
- parts.push("const ");
- }
+ case "DoExpression":
+ return [node.async ? "async " : "", "do ", print("body")];
- parts.push("enum ", path.call(print, "id"), " ");
+ case "BreakStatement":
+ parts.push("break");
- if (n.members.length === 0) {
- parts.push(group$l(concat$x(["{", comments.printDanglingComments(path, options), softline$h, "}"])));
- } else {
- parts.push(group$l(concat$x(["{", indent$p(concat$x([hardline$k, printArrayItems$1(path, options, "members", print), shouldPrintComma$8(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), hardline$k, "}"])));
+ if (node.label) {
+ parts.push(" ", print("label"));
}
- return concat$x(parts);
+ parts.push(semi);
+ return parts;
- case "TSEnumMember":
- parts.push(path.call(print, "id"));
+ case "ContinueStatement":
+ parts.push("continue");
- if (n.initializer) {
- parts.push(" = ", path.call(print, "initializer"));
+ if (node.label) {
+ parts.push(" ", print("label"));
}
- return concat$x(parts);
+ parts.push(semi);
+ return parts;
- case "TSImportEqualsDeclaration":
- if (n.isExport) {
- parts.push("export ");
+ case "LabeledStatement":
+ if (node.body.type === "EmptyStatement") {
+ return [print("label"), ":;"];
}
- parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
+ return [print("label"), ": ", print("body")];
- if (options.semi) {
- parts.push(";");
+ case "TryStatement":
+ return ["try ", print("block"), node.handler ? [" ", print("handler")] : "", node.finalizer ? [" finally ", print("finalizer")] : ""];
+
+ case "CatchClause":
+ if (node.param) {
+ const parameterHasComments = hasComment(node.param, comment => !isBlockComment(comment) || comment.leading && hasNewline$1(options.originalText, locEnd$e(comment)) || comment.trailing && hasNewline$1(options.originalText, locStart$f(comment), {
+ backwards: true
+ }));
+ const param = print("param");
+ return ["catch ", parameterHasComments ? ["(", indent$8([softline$a, param]), softline$a, ") "] : ["(", param, ") "], print("body")];
}
- return group$l(concat$x(parts));
+ return ["catch ", print("body")];
+ // Note: ignoring n.lexical because it has no printing consequences.
- case "TSExternalModuleReference":
- return concat$x(["require(", path.call(print, "expression"), ")"]);
+ case "SwitchStatement":
+ return [group$e(["switch (", indent$8([softline$a, print("discriminant")]), softline$a, ")"]), " {", node.cases.length > 0 ? indent$8([hardline$g, join$c(hardline$g, path.map((casePath, index, cases) => {
+ const caseNode = casePath.getValue();
+ return [print(), index !== cases.length - 1 && isNextLineEmpty$4(caseNode, options) ? hardline$g : ""];
+ }, "cases"))]) : "", hardline$g, "}"];
- case "TSModuleDeclaration":
+ case "SwitchCase":
{
- const parent = path.getParentNode();
- const isExternalModule = isLiteral$2(n.id);
- const parentIsDeclaration = parent.type === "TSModuleDeclaration";
- const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
-
- if (parentIsDeclaration) {
- parts.push(".");
+ if (node.test) {
+ parts.push("case ", print("test"), ":");
} else {
- if (n.declare) {
- parts.push("declare ");
- }
-
- parts.push(printTypeScriptModifiers$2(path, options, print));
- const textBetweenNodeAndItsId = options.originalText.slice(locStart$8(n), locStart$8(n.id)); // Global declaration looks like this:
- // (declare)? global { ... }
-
- const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
-
- if (!isGlobalDeclaration) {
- parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
- }
+ parts.push("default:");
}
- parts.push(path.call(print, "id"));
+ const consequent = node.consequent.filter(node => node.type !== "EmptyStatement");
- if (bodyIsDeclaration) {
- parts.push(path.call(print, "body"));
- } else if (n.body) {
- parts.push(" ", group$l(path.call(print, "body")));
- } else {
- parts.push(semi);
+ if (consequent.length > 0) {
+ const cons = printSwitchCaseConsequent(path, options, print);
+ parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? [" ", cons] : indent$8([hardline$g, cons]));
}
- return concat$x(parts);
+ return parts;
}
+ // JSX extensions below.
- case "PrivateName":
- // babel use `id`, meriyah use `name`
- return concat$x(["#", path.call(print, n.id ? "id" : "name")]);
- // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
-
- case "TSPrivateIdentifier":
- return n.escapedText;
-
- case "TSConditionalType":
- return ternary(path, options, print, {
- beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
- afterParts: () => [],
- shouldCheckJsx: false,
- conditionalNodeType: "TSConditionalType",
- consequentNodePropertyName: "trueType",
- alternateNodePropertyName: "falseType",
- testNodePropertyNames: ["checkType", "extendsType"]
- });
-
- case "TSInferType":
- return concat$x(["infer", " ", path.call(print, "typeParameter")]);
-
- case "InterpreterDirective":
- parts.push("#!", n.value, hardline$k);
+ case "DebuggerStatement":
+ return ["debugger", semi];
- if (isNextLineEmpty$9(options.originalText, n, locEnd$e)) {
- parts.push(hardline$k);
- }
+ case "ClassDeclaration":
+ case "ClassExpression":
+ return printClass(path, options, print);
- return concat$x(parts);
+ case "ClassMethod":
+ case "ClassPrivateMethod":
+ case "MethodDefinition":
+ return printClassMethod(path, options, print);
- case "NGRoot":
- return concat$x([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$x([" //", n.node.comments[0].value.trimEnd()])));
+ case "ClassProperty":
+ case "PropertyDefinition":
+ case "ClassPrivateProperty":
+ return printClassProperty(path, options, print);
- case "NGChainedExpression":
- return group$l(join$f(concat$x([";", line$j]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$x(["(", print(childPath), ")"]), "expressions")));
+ case "TemplateElement":
+ return replaceTextEndOfLine$9(node.value.raw);
- case "NGEmptyExpression":
- return "";
+ case "TemplateLiteral":
+ return printTemplateLiteral(path, print, options);
- case "NGQuotedExpression":
- return concat$x([n.prefix, ": ", n.value.trim()]);
+ case "TaggedTemplateExpression":
+ return [print("tag"), print("typeParameters"), print("quasi")];
- case "NGMicrosyntax":
- return concat$x(path.map((childPath, index) => concat$x([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$x([";", line$j]), print(childPath)]), "body"));
+ case "PrivateIdentifier":
+ return ["#", print("name")];
- case "NGMicrosyntaxKey":
- return /^[$_a-z][\w$]*(-[$_a-z][\w$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
+ case "PrivateName":
+ return ["#", print("id")];
- case "NGMicrosyntaxExpression":
- return concat$x([path.call(print, "expression"), n.alias === null ? "" : concat$x([" as ", path.call(print, "alias")])]);
+ case "InterpreterDirective":
+ parts.push("#!", node.value, hardline$g);
- case "NGMicrosyntaxKeyedExpression":
- {
- const index = path.getName();
- const parentNode = path.getParentNode();
- const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
- return concat$x([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
+ if (isNextLineEmpty$4(node, options)) {
+ parts.push(hardline$g);
}
- case "NGMicrosyntaxLet":
- return concat$x(["let ", path.call(print, "key"), n.value === null ? "" : concat$x([" = ", path.call(print, "value")])]);
-
- case "NGMicrosyntaxAs":
- return concat$x([path.call(print, "key"), " as ", path.call(print, "alias")]);
-
- case "PipelineBareFunction":
- return path.call(print, "callee");
+ return parts;
+ // For hack-style pipeline
- case "PipelineTopicExpression":
- return path.call(print, "expression");
-
- case "PipelinePrimaryTopicReference":
- {
- parts.push("#");
- return concat$x(parts);
- }
+ case "TopicReference":
+ return "%";
case "ArgumentPlaceholder":
return "?";
- // These are not valid TypeScript. Printing them just for the sake of error recovery.
-
- case "TSJSDocAllType":
- return "*";
-
- case "TSJSDocUnknownType":
- return "?";
- case "TSJSDocNullableType":
- return concat$x(["?", path.call(print, "typeAnnotation")]);
+ case "ModuleExpression":
+ {
+ parts.push("module {");
+ const printed = print("body");
- case "TSJSDocNonNullableType":
- return concat$x(["!", path.call(print, "typeAnnotation")]);
+ if (printed) {
+ parts.push(indent$8([hardline$g, printed]), hardline$g);
+ }
- case "TSJSDocFunctionType":
- return concat$x(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
- "): ", path.call(print, "typeAnnotation")]);
+ parts.push("}");
+ return parts;
+ }
default:
/* istanbul ignore next */
- throw new Error("unknown type: " + JSON.stringify(n.type));
+ throw new Error("unknown type: " + JSON.stringify(node.type));
}
}
-function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
- const raw = rawText$3(node);
- const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
- return printString$2(raw, options, isDirectiveLiteral);
-}
+function printDirective(node, options) {
+ const raw = rawText(node);
+ const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
+ // the quotes on a DirectiveLiteral.
+
+ if (rawContent.includes('"') || rawContent.includes("'")) {
+ return raw;
+ }
-function printRegex(node) {
- const flags = node.flags.split("").sort().join("");
- return `/${node.pattern}/${flags}`;
+ const enclosingQuote = options.singleQuote ? "'" : '"'; // Directives are exact code unit sequences, which means that you can't
+ // change the escape sequences they use.
+ // See https://github.com/prettier/prettier/issues/1555
+ // and https://tc39.github.io/ecma262/#directive-prologue
+
+ return enclosingQuote + rawContent + enclosingQuote;
}
-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";
+function canAttachComment$1(node) {
+ return node.type && !isBlockComment(node) && !isLineComment(node) && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import" && // `babel-ts` don't have similar node for `class Foo { bar() /* bat */; }`
+ node.type !== "TSEmptyBodyFunctionExpression";
}
var printerEstree = {
- preprocess: printPreprocess,
- print: genericPrint,
- embed: embed_1,
- insertPragma: insertPragma$1,
- massageAstNode: clean_1,
- hasPrettierIgnore: hasPrettierIgnore$1,
- willPrintOwnComments: comments$1.willPrintOwnComments,
- canAttachComment,
- printComment: printComment$2,
- isBlockComment: isBlockComment$9,
+ preprocess: preprocess$7,
+ print: genericPrint$6,
+ embed: embed$9,
+ insertPragma: insertPragma$9,
+ massageAstNode: clean$b,
+
+ hasPrettierIgnore(path) {
+ return hasIgnoreComment(path) || hasJsxIgnoreComment(path);
+ },
+
+ willPrintOwnComments: handleComments.willPrintOwnComments,
+ canAttachComment: canAttachComment$1,
+ printComment: printComment$1,
+ isBlockComment,
handleComments: {
- ownLine: comments$1.handleOwnLineComment,
- endOfLine: comments$1.handleEndOfLineComment,
- remaining: comments$1.handleRemainingComment
+ // TODO: Make this as default behavior
+ avoidAstMutation: true,
+ ownLine: handleComments.handleOwnLineComment,
+ endOfLine: handleComments.handleEndOfLineComment,
+ remaining: handleComments.handleRemainingComment
},
- getGapRegex: comments$1.getGapRegex,
- getCommentChildNodes: comments$1.getCommentChildNodes
+ getCommentChildNodes: handleComments.getCommentChildNodes
};
const {
builders: {
- concat: concat$y,
- hardline: hardline$l,
- indent: indent$q,
- join: join$g
+ hardline: hardline$f,
+ indent: indent$7,
+ join: join$b
}
-} = document;
+} = require$$7$3;
+const preprocess$6 = printPreprocess$3;
-function genericPrint$1(path, options, print) {
+function genericPrint$5(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "JsonRoot":
- return concat$y([path.call(print, "node"), hardline$l]);
+ return [print("node"), hardline$f];
case "ArrayExpression":
- return node.elements.length === 0 ? "[]" : concat$y(["[", indent$q(concat$y([hardline$l, join$g(concat$y([",", hardline$l]), path.map(print, "elements"))])), hardline$l, "]"]);
+ {
+ if (node.elements.length === 0) {
+ return "[]";
+ }
+
+ const printed = path.map(() => path.getValue() === null ? "null" : print(), "elements");
+ return ["[", indent$7([hardline$f, join$b([",", hardline$f], printed)]), hardline$f, "]"];
+ }
case "ObjectExpression":
- return node.properties.length === 0 ? "{}" : concat$y(["{", indent$q(concat$y([hardline$l, join$g(concat$y([",", hardline$l]), path.map(print, "properties"))])), hardline$l, "}"]);
+ return node.properties.length === 0 ? "{}" : ["{", indent$7([hardline$f, join$b([",", hardline$f], path.map(print, "properties"))]), hardline$f, "}"];
case "ObjectProperty":
- return concat$y([path.call(print, "key"), ": ", path.call(print, "value")]);
+ return [print("key"), ": ", print("value")];
case "UnaryExpression":
- return concat$y([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
+ return [node.operator === "+" ? "" : node.operator, print("argument")];
case "NullLiteral":
return "null";
@@ -47187,7 +49592,22 @@ function genericPrint$1(path, options, print) {
return JSON.stringify(node.value);
case "Identifier":
- return JSON.stringify(node.name);
+ {
+ const parent = path.getParentNode();
+
+ if (parent && parent.type === "ObjectProperty" && parent.key === node) {
+ return JSON.stringify(node.name);
+ }
+
+ return node.name;
+ }
+
+ case "TemplateLiteral":
+ // There is only one `TemplateElement`
+ return print(["quasis", 0]);
+
+ case "TemplateElement":
+ return JSON.stringify(node.value.cooked);
default:
/* istanbul ignore next */
@@ -47195,37 +49615,59 @@ function genericPrint$1(path, options, print) {
}
}
-const ignoredProperties$1 = new Set(["start", "end", "extra", "loc", "comments", "errors", "range"]);
+const ignoredProperties$3 = new Set(["start", "end", "extra", "loc", "comments", "leadingComments", "trailingComments", "innerComments", "errors", "range", "tokens"]);
-function clean$1(node, newNode
+function clean$a(node, newNode
/*, parent*/
) {
const {
type
- } = node;
+ } = node; // We print quoted key
- if (type === "Identifier") {
- return {
+ if (type === "ObjectProperty" && node.key.type === "Identifier") {
+ newNode.key = {
type: "StringLiteral",
- value: node.name
+ value: node.key.name
};
+ return;
}
if (type === "UnaryExpression" && node.operator === "+") {
return newNode.argument;
+ } // We print holes in array as `null`
+
+
+ if (type === "ArrayExpression") {
+ for (const [index, element] of node.elements.entries()) {
+ if (element === null) {
+ newNode.elements.splice(index, 0, {
+ type: "NullLiteral"
+ });
+ }
+ }
+
+ return;
+ } // We print `TemplateLiteral` as string
+
+
+ if (type === "TemplateLiteral") {
+ return {
+ type: "StringLiteral",
+ value: node.quasis[0].value.cooked
+ };
}
}
-clean$1.ignoredProperties = ignoredProperties$1;
+clean$a.ignoredProperties = ignoredProperties$3;
var printerEstreeJson = {
- preprocess: printPreprocess,
- print: genericPrint$1,
- massageAstNode: clean$1
+ preprocess: preprocess$6,
+ print: genericPrint$5,
+ massageAstNode: clean$a
};
-const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
+const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
-var commonOptions = {
+var commonOptions$6 = {
bracketSpacing: {
since: "0.0.0",
category: CATEGORY_COMMON,
@@ -47266,12 +49708,20 @@ var commonOptions = {
value: "preserve",
description: "Wrap prose as-is."
}]
+ },
+ bracketSameLine: {
+ since: "2.4.0",
+ category: CATEGORY_COMMON,
+ type: "boolean",
+ default: false,
+ description: "Put > of opening tags on the last line instead of on a new line."
}
};
-const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
+const commonOptions$5 = commonOptions$6;
+const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
-var options$2 = {
+var options$b = {
arrowParens: {
since: "1.9.0",
category: CATEGORY_JAVASCRIPT,
@@ -47292,13 +49742,14 @@ var options$2 = {
description: "Omit parens when possible. Example: `x => x`"
}]
},
- bracketSpacing: commonOptions.bracketSpacing,
+ bracketSameLine: commonOptions$5.bracketSameLine,
+ bracketSpacing: commonOptions$5.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."
+ description: "Put > on the last line instead of at a new line.",
+ deprecated: "2.4.0"
},
semi: {
since: "1.0.0",
@@ -47308,7 +49759,7 @@ var options$2 = {
description: "Print semicolons.",
oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
},
- singleQuote: commonOptions.singleQuote,
+ singleQuote: commonOptions$5.singleQuote,
jsxSingleQuote: {
since: "1.15.0",
category: CATEGORY_JAVASCRIPT,
@@ -47361,18 +49812,115 @@ var options$2 = {
}
};
-var name$2 = "JavaScript";
-var type = "programming";
-var tmScope = "source.js";
-var aceMode = "javascript";
-var codemirrorMode = "javascript";
-var codemirrorMimeType = "text/javascript";
-var color = "#f1e05a";
-var aliases = [
+var require$$0$2 = require("./parser-babel.js");
+
+var require$$1$1 = require("./parser-flow.js");
+
+var require$$2$1 = require("./parser-typescript.js");
+
+var require$$3$1 = require("./parser-angular.js");
+
+var require$$4$6 = require("./parser-espree.js");
+
+var require$$5$3 = require("./parser-meriyah.js");
+
+var parsers$d = {
+ // JS - Babel
+ get babel() {
+ return require$$0$2.parsers.babel;
+ },
+
+ get "babel-flow"() {
+ return require$$0$2.parsers["babel-flow"];
+ },
+
+ get "babel-ts"() {
+ return require$$0$2.parsers["babel-ts"];
+ },
+
+ get json() {
+ return require$$0$2.parsers.json;
+ },
+
+ get json5() {
+ return require$$0$2.parsers.json5;
+ },
+
+ get "json-stringify"() {
+ return require$$0$2.parsers["json-stringify"];
+ },
+
+ get __js_expression() {
+ return require$$0$2.parsers.__js_expression;
+ },
+
+ get __vue_expression() {
+ return require$$0$2.parsers.__vue_expression;
+ },
+
+ get __vue_event_binding() {
+ return require$$0$2.parsers.__vue_event_binding;
+ },
+
+ // JS - Flow
+ get flow() {
+ return require$$1$1.parsers.flow;
+ },
+
+ // JS - TypeScript
+ get typescript() {
+ return require$$2$1.parsers.typescript;
+ },
+
+ // JS - Angular Action
+ get __ng_action() {
+ return require$$3$1.parsers.__ng_action;
+ },
+
+ // JS - Angular Binding
+ get __ng_binding() {
+ return require$$3$1.parsers.__ng_binding;
+ },
+
+ // JS - Angular Interpolation
+ get __ng_interpolation() {
+ return require$$3$1.parsers.__ng_interpolation;
+ },
+
+ // JS - Angular Directive
+ get __ng_directive() {
+ return require$$3$1.parsers.__ng_directive;
+ },
+
+ // JS - espree
+ get espree() {
+ return require$$4$6.parsers.espree;
+ },
+
+ // JS - meriyah
+ get meriyah() {
+ return require$$5$3.parsers.meriyah;
+ },
+
+ // JS - Babel Estree
+ get __babel_estree() {
+ return require$$0$2.parsers.__babel_estree;
+ }
+
+};
+
+var name$f = "JavaScript";
+var type$f = "programming";
+var tmScope$f = "source.js";
+var aceMode$f = "javascript";
+var codemirrorMode$b = "javascript";
+var codemirrorMimeType$b = "text/javascript";
+var color$a = "#f1e05a";
+var aliases$6 = [
"js",
"node"
];
-var extensions = [
+var extensions$f = [
".js",
"._js",
".bones",
@@ -47387,6 +49935,7 @@ var extensions = [
".jsfl",
".jsm",
".jss",
+ ".jsx",
".mjs",
".njs",
".pac",
@@ -47395,10 +49944,10 @@ var extensions = [
".xsjs",
".xsjslib"
];
-var filenames = [
+var filenames$4 = [
"Jakefile"
];
-var interpreters = [
+var interpreters$1 = [
"chakra",
"d8",
"gjs",
@@ -47410,108 +49959,84 @@ var interpreters = [
"v8",
"v8-shell"
];
-var languageId = 183;
-var require$$0$2 = {
- name: name$2,
- type: type,
- tmScope: tmScope,
- aceMode: aceMode,
- codemirrorMode: codemirrorMode,
- codemirrorMimeType: codemirrorMimeType,
- color: color,
- aliases: aliases,
- extensions: extensions,
- filenames: filenames,
- interpreters: interpreters,
- languageId: languageId
-};
-
-var name$3 = "JSX";
-var type$1 = "programming";
-var group$m = "JavaScript";
-var extensions$1 = [
- ".jsx"
-];
-var tmScope$1 = "source.js.jsx";
-var aceMode$1 = "javascript";
-var codemirrorMode$1 = "jsx";
-var codemirrorMimeType$1 = "text/jsx";
-var languageId$1 = 178;
-var require$$1 = {
- name: name$3,
- type: type$1,
- group: group$m,
- extensions: extensions$1,
- tmScope: tmScope$1,
- aceMode: aceMode$1,
- codemirrorMode: codemirrorMode$1,
- codemirrorMimeType: codemirrorMimeType$1,
- languageId: languageId$1
+var languageId$f = 183;
+var require$$5$2 = {
+ name: name$f,
+ type: type$f,
+ tmScope: tmScope$f,
+ aceMode: aceMode$f,
+ codemirrorMode: codemirrorMode$b,
+ codemirrorMimeType: codemirrorMimeType$b,
+ color: color$a,
+ aliases: aliases$6,
+ extensions: extensions$f,
+ filenames: filenames$4,
+ interpreters: interpreters$1,
+ languageId: languageId$f
};
-var name$4 = "TypeScript";
-var type$2 = "programming";
-var color$1 = "#2b7489";
-var aliases$1 = [
+var name$e = "TypeScript";
+var type$e = "programming";
+var color$9 = "#2b7489";
+var aliases$5 = [
"ts"
];
-var interpreters$1 = [
+var interpreters = [
"deno",
"ts-node"
];
-var extensions$2 = [
+var extensions$e = [
".ts"
];
-var tmScope$2 = "source.ts";
-var aceMode$2 = "typescript";
-var codemirrorMode$2 = "javascript";
-var codemirrorMimeType$2 = "application/typescript";
-var languageId$2 = 378;
-var require$$2 = {
- name: name$4,
- type: type$2,
- color: color$1,
- aliases: aliases$1,
- interpreters: interpreters$1,
- extensions: extensions$2,
- tmScope: tmScope$2,
- aceMode: aceMode$2,
- codemirrorMode: codemirrorMode$2,
- codemirrorMimeType: codemirrorMimeType$2,
- languageId: languageId$2
+var tmScope$e = "source.ts";
+var aceMode$e = "typescript";
+var codemirrorMode$a = "javascript";
+var codemirrorMimeType$a = "application/typescript";
+var languageId$e = 378;
+var require$$6$1 = {
+ name: name$e,
+ type: type$e,
+ color: color$9,
+ aliases: aliases$5,
+ interpreters: interpreters,
+ extensions: extensions$e,
+ tmScope: tmScope$e,
+ aceMode: aceMode$e,
+ codemirrorMode: codemirrorMode$a,
+ codemirrorMimeType: codemirrorMimeType$a,
+ languageId: languageId$e
};
-var name$5 = "TSX";
-var type$3 = "programming";
-var group$n = "TypeScript";
-var extensions$3 = [
+var name$d = "TSX";
+var type$d = "programming";
+var group$d = "TypeScript";
+var extensions$d = [
".tsx"
];
-var tmScope$3 = "source.tsx";
-var aceMode$3 = "javascript";
-var codemirrorMode$3 = "jsx";
-var codemirrorMimeType$3 = "text/jsx";
-var languageId$3 = 94901924;
-var require$$3 = {
- name: name$5,
- type: type$3,
- group: group$n,
- extensions: extensions$3,
- tmScope: tmScope$3,
- aceMode: aceMode$3,
- codemirrorMode: codemirrorMode$3,
- codemirrorMimeType: codemirrorMimeType$3,
- languageId: languageId$3
+var tmScope$d = "source.tsx";
+var aceMode$d = "javascript";
+var codemirrorMode$9 = "jsx";
+var codemirrorMimeType$9 = "text/jsx";
+var languageId$d = 94901924;
+var require$$7$1 = {
+ name: name$d,
+ type: type$d,
+ group: group$d,
+ extensions: extensions$d,
+ tmScope: tmScope$d,
+ aceMode: aceMode$d,
+ codemirrorMode: codemirrorMode$9,
+ codemirrorMimeType: codemirrorMimeType$9,
+ languageId: languageId$d
};
-var name$6 = "JSON";
-var type$4 = "data";
-var tmScope$4 = "source.json";
-var aceMode$4 = "json";
-var codemirrorMode$4 = "javascript";
-var codemirrorMimeType$4 = "application/json";
-var searchable = false;
-var extensions$4 = [
+var name$c = "JSON";
+var type$c = "data";
+var tmScope$c = "source.json";
+var aceMode$c = "json";
+var codemirrorMode$8 = "javascript";
+var codemirrorMimeType$8 = "application/json";
+var extensions$c = [
".json",
".avsc",
".geojson",
@@ -47529,40 +50054,41 @@ var extensions$4 = [
".yy",
".yyp"
];
-var filenames$1 = [
+var filenames$3 = [
".arcconfig",
".htmlhintrc",
+ ".imgbotconfig",
".tern-config",
".tern-project",
".watchmanconfig",
+ "Pipfile.lock",
"composer.lock",
"mcmod.info"
];
-var languageId$4 = 174;
-var require$$4$1 = {
- name: name$6,
- type: type$4,
- tmScope: tmScope$4,
- aceMode: aceMode$4,
- codemirrorMode: codemirrorMode$4,
- codemirrorMimeType: codemirrorMimeType$4,
- searchable: searchable,
- extensions: extensions$4,
- filenames: filenames$1,
- languageId: languageId$4
+var languageId$c = 174;
+var require$$8 = {
+ name: name$c,
+ type: type$c,
+ tmScope: tmScope$c,
+ aceMode: aceMode$c,
+ codemirrorMode: codemirrorMode$8,
+ codemirrorMimeType: codemirrorMimeType$8,
+ extensions: extensions$c,
+ filenames: filenames$3,
+ languageId: languageId$c
};
-var name$7 = "JSON with Comments";
-var type$5 = "data";
-var group$o = "JSON";
-var tmScope$5 = "source.js";
-var aceMode$5 = "javascript";
-var codemirrorMode$5 = "javascript";
-var codemirrorMimeType$5 = "text/javascript";
-var aliases$2 = [
+var name$b = "JSON with Comments";
+var type$b = "data";
+var group$c = "JSON";
+var tmScope$b = "source.js";
+var aceMode$b = "javascript";
+var codemirrorMode$7 = "javascript";
+var codemirrorMimeType$7 = "text/javascript";
+var aliases$4 = [
"jsonc"
];
-var extensions$5 = [
+var extensions$b = [
".jsonc",
".sublime-build",
".sublime-commands",
@@ -47584,56 +50110,64 @@ var filenames$2 = [
".jscsrc",
".jshintrc",
".jslintrc",
+ "api-extractor.json",
"devcontainer.json",
"jsconfig.json",
"language-configuration.json",
"tsconfig.json",
"tslint.json"
];
-var languageId$5 = 423;
-var require$$5 = {
- name: name$7,
- type: type$5,
- group: group$o,
- tmScope: tmScope$5,
- aceMode: aceMode$5,
- codemirrorMode: codemirrorMode$5,
- codemirrorMimeType: codemirrorMimeType$5,
- aliases: aliases$2,
- extensions: extensions$5,
+var languageId$b = 423;
+var require$$9 = {
+ name: name$b,
+ type: type$b,
+ group: group$c,
+ tmScope: tmScope$b,
+ aceMode: aceMode$b,
+ codemirrorMode: codemirrorMode$7,
+ codemirrorMimeType: codemirrorMimeType$7,
+ aliases: aliases$4,
+ extensions: extensions$b,
filenames: filenames$2,
- languageId: languageId$5
+ languageId: languageId$b
};
-var name$8 = "JSON5";
-var type$6 = "data";
-var extensions$6 = [
+var name$a = "JSON5";
+var type$a = "data";
+var extensions$a = [
".json5"
];
-var tmScope$6 = "source.js";
-var aceMode$6 = "javascript";
+var tmScope$a = "source.js";
+var aceMode$a = "javascript";
var codemirrorMode$6 = "javascript";
var codemirrorMimeType$6 = "application/json";
-var languageId$6 = 175;
-var require$$6 = {
- name: name$8,
- type: type$6,
- extensions: extensions$6,
- tmScope: tmScope$6,
- aceMode: aceMode$6,
+var languageId$a = 175;
+var require$$10 = {
+ name: name$a,
+ type: type$a,
+ extensions: extensions$a,
+ tmScope: tmScope$a,
+ aceMode: aceMode$a,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
- languageId: languageId$6
+ languageId: languageId$a
};
-const languages = [createLanguage(require$$0$2, data => ({
+const createLanguage$6 = createLanguage$7;
+const estreePrinter = printerEstree;
+const estreeJsonPrinter = printerEstreeJson;
+const options$a = options$b;
+const parsers$c = parsers$d;
+const languages$7 = [createLanguage$6(require$$5$2, data => ({
since: "0.0.0",
parsers: ["babel", "espree", "meriyah", "babel-flow", "babel-ts", "flow", "typescript"],
vscodeLanguageIds: ["javascript", "mongo"],
- extensions: [...data.extensions, // WeiXin Script (Weixin Mini Programs)
+ interpreters: [...data.interpreters, // https://github.com/google/zx
+ "zx"],
+ extensions: [...data.extensions.filter(extension => extension !== ".jsx"), // WeiXin Script (Weixin Mini Programs)
// https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/
".wxs"]
-})), createLanguage(require$$0$2, () => ({
+})), createLanguage$6(require$$5$2, () => ({
name: "Flow",
since: "0.0.0",
parsers: ["flow", "babel-flow"],
@@ -47641,19 +50175,31 @@ const languages = [createLanguage(require$$0$2, data => ({
aliases: [],
filenames: [],
extensions: [".js.flow"]
-})), createLanguage(require$$1, () => ({
+})), createLanguage$6(require$$5$2, () => ({
+ name: "JSX",
since: "0.0.0",
parsers: ["babel", "babel-flow", "babel-ts", "flow", "typescript", "espree", "meriyah"],
- vscodeLanguageIds: ["javascriptreact"]
-})), createLanguage(require$$2, () => ({
+ vscodeLanguageIds: ["javascriptreact"],
+ aliases: undefined,
+ filenames: undefined,
+ extensions: [".jsx"],
+ group: "JavaScript",
+ interpreters: undefined,
+ tmScope: "source.js.jsx",
+ aceMode: "javascript",
+ codemirrorMode: "jsx",
+ codemirrorMimeType: "text/jsx",
+ color: undefined
+})), createLanguage$6(require$$6$1, data => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
- vscodeLanguageIds: ["typescript"]
-})), createLanguage(require$$3, () => ({
+ vscodeLanguageIds: ["typescript"],
+ extensions: [...data.extensions, ".mts", ".cts"]
+})), createLanguage$6(require$$7$1, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescriptreact"]
-})), createLanguage(require$$4$1, () => ({
+})), createLanguage$6(require$$8, () => ({
name: "JSON.stringify",
since: "1.13.0",
parsers: ["json-stringify"],
@@ -47661,127 +50207,48 @@ const languages = [createLanguage(require$$0$2, data => ({
extensions: [],
// .json file defaults to json instead of json-stringify
filenames: ["package.json", "package-lock.json", "composer.json"]
-})), createLanguage(require$$4$1, data => ({
+})), createLanguage$6(require$$8, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["json"],
- filenames: [...data.filenames, ".prettierrc"],
extensions: data.extensions.filter(extension => extension !== ".jsonl")
-})), createLanguage(require$$5, data => ({
+})), createLanguage$6(require$$9, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["jsonc"],
filenames: [...data.filenames, ".eslintrc"]
-})), createLanguage(require$$6, () => ({
+})), createLanguage$6(require$$10, () => ({
since: "1.13.0",
parsers: ["json5"],
vscodeLanguageIds: ["json5"]
}))];
-const printers = {
- estree: printerEstree,
- "estree-json": printerEstreeJson
-};
-const parsers = {
- // JS - Babel
- get babel() {
- return require("./parser-babel").parsers.babel;
- },
-
- get "babel-flow"() {
- return require("./parser-babel").parsers["babel-flow"];
- },
-
- get "babel-ts"() {
- return require("./parser-babel").parsers["babel-ts"];
- },
-
- get json() {
- return require("./parser-babel").parsers.json;
- },
-
- get json5() {
- return require("./parser-babel").parsers.json5;
- },
-
- get "json-stringify"() {
- return require("./parser-babel").parsers["json-stringify"];
- },
-
- get __js_expression() {
- return require("./parser-babel").parsers.__js_expression;
- },
-
- get __vue_expression() {
- return require("./parser-babel").parsers.__vue_expression;
- },
-
- get __vue_event_binding() {
- return require("./parser-babel").parsers.__vue_event_binding;
- },
-
- // JS - Flow
- get flow() {
- return require("./parser-flow").parsers.flow;
- },
-
- // JS - TypeScript
- get typescript() {
- return require("./parser-typescript").parsers.typescript;
- },
-
- // JS - Angular Action
- get __ng_action() {
- return require("./parser-angular").parsers.__ng_action;
- },
-
- // JS - Angular Binding
- get __ng_binding() {
- return require("./parser-angular").parsers.__ng_binding;
- },
-
- // JS - Angular Interpolation
- get __ng_interpolation() {
- return require("./parser-angular").parsers.__ng_interpolation;
- },
-
- // JS - Angular Directive
- get __ng_directive() {
- return require("./parser-angular").parsers.__ng_directive;
- },
-
- // JS - espree
- get espree() {
- return require("./parser-espree").parsers.espree;
- },
-
- // JS - meriyah
- get meriyah() {
- return require("./parser-meriyah").parsers.meriyah;
- }
-
+const printers$5 = {
+ estree: estreePrinter,
+ "estree-json": estreeJsonPrinter
};
var languageJs = {
- languages,
- options: options$2,
- printers,
- parsers
+ languages: languages$7,
+ options: options$a,
+ printers: printers$5,
+ parsers: parsers$c
};
const {
- isFrontMatterNode: isFrontMatterNode$1
-} = util;
+ isFrontMatterNode: isFrontMatterNode$4
+} = util$8;
+const getLast$9 = getLast_1;
const ignoredProperties$2 = new Set(["raw", // front-matter
"raws", "sourceIndex", "source", "before", "after", "trailingComma"]);
-function clean$2(ast, newObj, parent) {
- if (isFrontMatterNode$1(ast) && ast.lang === "yaml") {
+function clean$9(ast, newObj, parent) {
+ if (isFrontMatterNode$4(ast) && ast.lang === "yaml") {
delete newObj.value;
}
- if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0) {
+ if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length > 0) {
// --insert-pragma
// first non-front-matter comment
- if (parent.nodes[0] === ast || isFrontMatterNode$1(parent.nodes[0]) && parent.nodes[1] === ast) {
+ if (parent.nodes[0] === ast || isFrontMatterNode$4(parent.nodes[0]) && parent.nodes[1] === ast) {
/**
* something
*
@@ -47789,13 +50256,13 @@ function clean$2(ast, newObj, parent) {
*/
delete newObj.text; // standalone pragma
- if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
+ if (/^\*\s*@(?:format|prettier)\s*$/.test(ast.text)) {
return null;
}
} // Last comment is not parsed, when omitting semicolon, #8675
- if (parent.type === "css-root" && getLast(parent.nodes) === ast) {
+ if (parent.type === "css-root" && getLast$9(parent.nodes) === ast) {
return null;
}
}
@@ -47862,7 +50329,7 @@ function clean$2(ast, newObj, parent) {
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, (match, numStr, unit) => {
const num = Number(numStr);
- return isNaN(num) ? match : num + unit.toLowerCase();
+ return Number.isNaN(num) ? match : num + unit.toLowerCase();
});
}
@@ -47885,55 +50352,20 @@ function clean$2(ast, newObj, parent) {
}
}
-clean$2.ignoredProperties = ignoredProperties$2;
+clean$9.ignoredProperties = ignoredProperties$2;
function cleanCSSStrings(value) {
return value.replace(/'/g, '"').replace(/\\([^\dA-Fa-f])/g, "$1");
}
-var clean_1$1 = clean$2;
+var clean_1$3 = clean$9;
const {
builders: {
- hardline: hardline$m,
- concat: concat$z,
- markAsRoot: markAsRoot$1
- }
-} = document;
-const DELIMITER_MAP = {
- "---": "yaml",
- "+++": "toml"
-};
-
-function parse$7(text) {
- const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
- const match = text.match( // trailing spaces after delimiters are allowed
- new RegExp(`^(${delimiterRegex})([^\\n]*)\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
-
- if (match === null) {
- return {
- frontMatter: null,
- content: text
- };
- }
-
- const [raw, delimiter, language, value] = match;
- let lang = DELIMITER_MAP[delimiter];
-
- if (lang !== "toml" && language && language.trim()) {
- lang = language.trim();
+ hardline: hardline$e,
+ markAsRoot: markAsRoot$3
}
-
- return {
- frontMatter: {
- type: "front-matter",
- lang,
- value,
- raw: raw.replace(/\n$/, "")
- },
- content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
- };
-}
+} = require$$7$3;
function print$1(node, textToDoc) {
if (node.lang === "yaml") {
@@ -47943,63 +50375,111 @@ function print$1(node, textToDoc) {
}, {
stripTrailingHardline: true
}) : "";
- return markAsRoot$1(concat$z(["---", hardline$m, doc, doc ? hardline$m : "", "---"]));
+ return markAsRoot$3([node.startDelimiter, hardline$e, doc, doc ? hardline$e : "", node.endDelimiter]);
}
}
-var frontMatter = {
- parse: parse$7,
- print: print$1
-};
+var print_1 = print$1;
const {
builders: {
- hardline: hardline$n,
- concat: concat$A
+ hardline: hardline$d
}
-} = document;
-const {
- print: printFrontMatter
-} = frontMatter;
+} = require$$7$3;
+const printFrontMatter$2 = print_1;
-function embed$1(path, print, textToDoc
+function embed$8(path, print, textToDoc
/*, options */
) {
const node = path.getValue();
if (node.type === "front-matter") {
- const doc = printFrontMatter(node, textToDoc);
- return doc ? concat$A([doc, hardline$n]) : "";
+ const doc = printFrontMatter$2(node, textToDoc);
+ return doc ? [doc, hardline$d] : "";
}
}
-var embed_1$1 = embed$1;
+var embed_1$3 = embed$8;
-const {
- parse: parseFrontMatter
-} = frontMatter;
+const frontMatterRegex = new RegExp("^(?-{3}|\\+{3})" + // trailing spaces after delimiters are allowed
+"(?[^\\n]*)" + "\\n(?:|(?.*?)\\n)" + // In some markdown processors such as pandoc,
+// "..." can be used as the end delimiter for YAML front-matter.
+// Adding `\.{3}` make the regex matches `+++\n...`, but we'll exclude it later
+"(?\\k|\\.{3})" + "[^\\S\\n]*(?:\\n|$)", "s");
-function hasPragma$1(text) {
- return pragma.hasPragma(parseFrontMatter(text).content);
+function parse(text) {
+ const match = text.match(frontMatterRegex);
+
+ if (!match) {
+ return {
+ content: text
+ };
+ }
+
+ const {
+ startDelimiter,
+ language,
+ value = "",
+ endDelimiter
+ } = match.groups;
+ let lang = language.trim() || "yaml";
+
+ if (startDelimiter === "+++") {
+ lang = "toml";
+ } // Only allow yaml to parse with a different end delimiter
+
+
+ if (lang !== "yaml" && startDelimiter !== endDelimiter) {
+ return {
+ content: text
+ };
+ }
+
+ const [raw] = match;
+ const frontMatter = {
+ type: "front-matter",
+ lang,
+ value,
+ startDelimiter,
+ endDelimiter,
+ raw: raw.replace(/\n$/, "")
+ };
+ return {
+ frontMatter,
+ content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
+ };
}
-function insertPragma$2(text) {
+var parse_1 = parse;
+
+const jsPragma = pragma$5;
+const parseFrontMatter$1 = parse_1;
+
+function hasPragma$3(text) {
+ return jsPragma.hasPragma(parseFrontMatter$1(text).content);
+}
+
+function insertPragma$8(text) {
const {
frontMatter,
content
- } = parseFrontMatter(text);
- return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma.insertPragma(content);
+ } = parseFrontMatter$1(text);
+ return (frontMatter ? frontMatter.raw + "\n\n" : "") + jsPragma.insertPragma(content);
}
-var pragma$1 = {
- hasPragma: hasPragma$1,
- insertPragma: insertPragma$2
+var pragma$4 = {
+ hasPragma: hasPragma$3,
+ insertPragma: insertPragma$8
};
+const {
+ isNonEmptyArray: isNonEmptyArray$6
+} = util$8;
const colorAdjusterFunctions = new Set(["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"]);
+const moduleRuleNames = new Set(["import", "use", "forward"]);
-function getAncestorCounter(path, typeOrTypes) {
- const types = [].concat(typeOrTypes);
+function getAncestorCounter$1(path, typeOrTypes) {
+ const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes];
let counter = -1;
let ancestorNode;
@@ -48012,18 +50492,18 @@ function getAncestorCounter(path, typeOrTypes) {
return -1;
}
-function getAncestorNode(path, typeOrTypes) {
- const counter = getAncestorCounter(path, typeOrTypes);
+function getAncestorNode$2(path, typeOrTypes) {
+ const counter = getAncestorCounter$1(path, typeOrTypes);
return counter === -1 ? null : path.getParentNode(counter);
}
-function getPropOfDeclNode(path) {
- const declAncestorNode = getAncestorNode(path, "css-decl");
+function getPropOfDeclNode$1(path) {
+ const declAncestorNode = getAncestorNode$2(path, "css-decl");
return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
}
function hasSCSSInterpolation(groupList) {
- if (groupList && groupList.length) {
+ if (isNonEmptyArray$6(groupList)) {
for (let i = groupList.length - 1; i > 0; i--) {
// If we find `#{`, return true.
if (groupList[i].type === "word" && groupList[i].value === "{" && groupList[i - 1].type === "word" && groupList[i - 1].value.endsWith("#")) {
@@ -48036,7 +50516,7 @@ function hasSCSSInterpolation(groupList) {
}
function hasStringOrFunction(groupList) {
- if (groupList && groupList.length) {
+ if (isNonEmptyArray$6(groupList)) {
for (let i = 0; i < groupList.length; i++) {
if (groupList[i].type === "string" || groupList[i].type === "func") {
return true;
@@ -48047,56 +50527,56 @@ function hasStringOrFunction(groupList) {
return false;
}
-function isSCSS(parser, text) {
+function isSCSS$1(parser, text) {
const hasExplicitParserChoice = parser === "less" || parser === "scss";
- const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/;
+ const IS_POSSIBLY_SCSS = /(?:\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/;
return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
}
function isSCSSVariable(node) {
- return !!(node && node.type === "word" && node.value.startsWith("$"));
+ return Boolean(node && node.type === "word" && node.value.startsWith("$"));
}
-function isWideKeywords(value) {
+function isWideKeywords$1(value) {
return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
}
-function isKeyframeAtRuleKeywords(path, value) {
- const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
+function isKeyframeAtRuleKeywords$1(path, value) {
+ const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
}
-function maybeToLowerCase(value) {
+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(path, functionName) {
- const funcAncestorNode = getAncestorNode(path, "value-func");
+function insideValueFunctionNode$1(path, functionName) {
+ const funcAncestorNode = getAncestorNode$2(path, "value-func");
return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
}
-function insideICSSRuleNode(path) {
- const ruleAncestorNode = getAncestorNode(path, "css-rule");
+function insideICSSRuleNode$1(path) {
+ const ruleAncestorNode = getAncestorNode$2(path, "css-rule");
return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
}
-function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
- const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
- const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
+function insideAtRuleNode$1(path, atRuleNameOrAtRuleNames) {
+ const atRuleNames = Array.isArray(atRuleNameOrAtRuleNames) ? atRuleNameOrAtRuleNames : [atRuleNameOrAtRuleNames];
+ const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule");
return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
}
-function insideURLFunctionInImportAtRuleNode(path) {
+function insideURLFunctionInImportAtRuleNode$1(path) {
const node = path.getValue();
- const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
+ const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
}
-function isURLFunctionNode(node) {
+function isURLFunctionNode$1(node) {
return node.type === "value-func" && node.value.toLowerCase() === "url";
}
-function isLastNode(path, node) {
+function isLastNode$1(path, node) {
const parentNode = path.getParentNode();
/* istanbul ignore next */
@@ -48110,7 +50590,7 @@ function isLastNode(path, node) {
return nodes && nodes.indexOf(node) === nodes.length - 1;
}
-function isDetachedRulesetDeclarationNode(node) {
+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.
@@ -48123,31 +50603,31 @@ function isDetachedRulesetDeclarationNode(node) {
return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
}
-function isForKeywordNode(node) {
+function isForKeywordNode$1(node) {
return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
}
-function isIfElseKeywordNode(node) {
+function isIfElseKeywordNode$1(node) {
return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
}
-function isEachKeywordNode(node) {
+function isEachKeywordNode$1(node) {
return node.type === "value-word" && node.value === "in";
}
-function isMultiplicationNode(node) {
+function isMultiplicationNode$1(node) {
return node.type === "value-operator" && node.value === "*";
}
-function isDivisionNode(node) {
+function isDivisionNode$1(node) {
return node.type === "value-operator" && node.value === "/";
}
-function isAdditionNode(node) {
+function isAdditionNode$1(node) {
return node.type === "value-operator" && node.value === "+";
}
-function isSubtractionNode(node) {
+function isSubtractionNode$1(node) {
return node.type === "value-operator" && node.value === "-";
}
@@ -48155,19 +50635,19 @@ function isModuloNode(node) {
return node.type === "value-operator" && node.value === "%";
}
-function isMathOperatorNode(node) {
- return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
+function isMathOperatorNode$1(node) {
+ return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node);
}
-function isEqualityOperatorNode(node) {
+function isEqualityOperatorNode$1(node) {
return node.type === "value-word" && ["==", "!="].includes(node.value);
}
-function isRelationalOperatorNode(node) {
+function isRelationalOperatorNode$1(node) {
return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
}
-function isSCSSControlDirectiveNode(node) {
+function isSCSSControlDirectiveNode$1(node) {
return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
}
@@ -48180,43 +50660,43 @@ function isSCSSNestedPropertyNode(node) {
return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
}
-function isDetachedRulesetCallNode(node) {
+function isDetachedRulesetCallNode$1(node) {
return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
}
-function isTemplatePlaceholderNode(node) {
+function isTemplatePlaceholderNode$1(node) {
return node.name.startsWith("prettier-placeholder");
}
-function isTemplatePropNode(node) {
+function isTemplatePropNode$1(node) {
return node.prop.startsWith("@prettier-placeholder");
}
-function isPostcssSimpleVarNode(currentNode, nextNode) {
+function isPostcssSimpleVarNode$1(currentNode, nextNode) {
return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
}
-function hasComposesNode(node) {
+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(node) {
+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(node) {
+function hasEmptyRawBefore$1(node) {
return node.raws && node.raws.before === "";
}
-function isKeyValuePairNode(node) {
+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(node.groups[0]);
+ return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]);
}
-function isSCSSMapItemNode(path) {
+function isSCSSMapItemNode$1(path) {
const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
if (node.groups.length === 0) {
@@ -48229,7 +50709,7 @@ function isSCSSMapItemNode(path) {
return false;
}
- const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
+ const declNode = getAncestorNode$2(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
return true;
@@ -48248,35 +50728,52 @@ function isSCSSMapItemNode(path) {
return false;
}
-function isInlineValueCommentNode(node) {
+function isInlineValueCommentNode$1(node) {
return node.type === "value-comment" && node.inline;
}
-function isHashNode(node) {
+function isHashNode$1(node) {
return node.type === "value-word" && node.value === "#";
}
-function isLeftCurlyBraceNode(node) {
+function isLeftCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "{";
}
-function isRightCurlyBraceNode(node) {
+function isRightCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "}";
}
-function isWordNode(node) {
+function isWordNode$1(node) {
return ["value-word", "value-atword"].includes(node.type);
}
-function isColonNode(node) {
- return node.type === "value-colon";
+function isColonNode$1(node) {
+ return node && node.type === "value-colon";
+}
+
+function isKeyInValuePairNode$1(node, parentNode) {
+ if (!isKeyValuePairNode$1(parentNode)) {
+ return false;
+ }
+
+ const {
+ groups
+ } = parentNode;
+ const index = groups.indexOf(node);
+
+ if (index === -1) {
+ return false;
+ }
+
+ return isColonNode$1(groups[index + 1]);
}
-function isMediaAndSupportsKeywords(node) {
+function isMediaAndSupportsKeywords$1(node) {
return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
}
-function isColorAdjusterFuncNode(node) {
+function isColorAdjusterFuncNode$1(node) {
if (node.type !== "value-func") {
return false;
}
@@ -48285,20 +50782,18 @@ function isColorAdjusterFuncNode(node) {
} // TODO: only check `less` when we don't use `less` to parse `css`
-function isLessParser(options) {
+function isLessParser$1(options) {
return options.parser === "css" || options.parser === "less";
}
-function lastLineHasInlineComment(text) {
+function lastLineHasInlineComment$1(text) {
return /\/\//.test(text.split(/[\n\r]/).pop());
}
function stringifyNode(node) {
if (node.groups) {
const open = node.open && node.open.value ? node.open.value : "";
- const groups = node.groups.reduce((previousValue, currentValue, index) => {
- return previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : "");
- }, "");
+ const groups = node.groups.reduce((previousValue, currentValue, index) => previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : ""), "");
const close = node.close && node.close.value ? node.close.value : "";
return open + groups + close;
}
@@ -48313,66 +50808,95 @@ function stringifyNode(node) {
return before + quote + atword + value + quote + unit + group + after;
}
-function isAtWordPlaceholderNode(node) {
+function isAtWordPlaceholderNode$1(node) {
return node && node.type === "value-atword" && node.value.startsWith("prettier-placeholder-");
}
-var utils$7 = {
- getAncestorCounter,
- getAncestorNode,
- getPropOfDeclNode,
+function isModuleRuleName(name) {
+ return moduleRuleNames.has(name);
+}
+
+function isConfigurationNode$1(node, parentNode) {
+ if (!node.open || node.open.value !== "(" || !node.close || node.close.value !== ")" || node.groups.some(group => group.type !== "value-comma_group")) {
+ return false;
+ }
+
+ if (parentNode.type === "value-comma_group") {
+ const prevIdx = parentNode.groups.indexOf(node) - 1;
+ const maybeWithNode = parentNode.groups[prevIdx];
+
+ if (maybeWithNode && maybeWithNode.type === "value-word" && maybeWithNode.value === "with") {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function isParenGroupNode$1(node) {
+ return node.type === "value-paren_group" && node.open && node.open.value === "(" && node.close && node.close.value === ")";
+}
+
+var utils$4 = {
+ getAncestorCounter: getAncestorCounter$1,
+ getAncestorNode: getAncestorNode$2,
+ getPropOfDeclNode: getPropOfDeclNode$1,
hasSCSSInterpolation,
hasStringOrFunction,
- maybeToLowerCase,
- insideValueFunctionNode,
- insideICSSRuleNode,
- insideAtRuleNode,
- insideURLFunctionInImportAtRuleNode,
- isKeyframeAtRuleKeywords,
- isWideKeywords,
- isSCSS,
+ maybeToLowerCase: maybeToLowerCase$1,
+ insideValueFunctionNode: insideValueFunctionNode$1,
+ insideICSSRuleNode: insideICSSRuleNode$1,
+ insideAtRuleNode: insideAtRuleNode$1,
+ insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
+ isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
+ isWideKeywords: isWideKeywords$1,
+ isSCSS: isSCSS$1,
isSCSSVariable,
- isLastNode,
- isLessParser,
- isSCSSControlDirectiveNode,
- isDetachedRulesetDeclarationNode,
- isRelationalOperatorNode,
- isEqualityOperatorNode,
- isMultiplicationNode,
- isDivisionNode,
- isAdditionNode,
- isSubtractionNode,
+ isLastNode: isLastNode$1,
+ isLessParser: isLessParser$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,
- isEachKeywordNode,
- isForKeywordNode,
- isURLFunctionNode,
- isIfElseKeywordNode,
- hasComposesNode,
- hasParensAroundNode,
- hasEmptyRawBefore,
+ 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,
- isTemplatePlaceholderNode,
- isTemplatePropNode,
- isPostcssSimpleVarNode,
- isKeyValuePairNode,
+ isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
+ isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
+ isTemplatePropNode: isTemplatePropNode$1,
+ isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
+ isKeyValuePairNode: isKeyValuePairNode$1,
isKeyValuePairInParenGroupNode,
- isSCSSMapItemNode,
- isInlineValueCommentNode,
- isHashNode,
- isLeftCurlyBraceNode,
- isRightCurlyBraceNode,
- isWordNode,
- isColonNode,
- isMediaAndSupportsKeywords,
- isColorAdjusterFuncNode,
- lastLineHasInlineComment,
+ isKeyInValuePairNode: isKeyInValuePairNode$1,
+ 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,
+ lastLineHasInlineComment: lastLineHasInlineComment$1,
stringifyNode,
- isAtWordPlaceholderNode
+ isAtWordPlaceholderNode: isAtWordPlaceholderNode$1,
+ isModuleRuleName,
+ isConfigurationNode: isConfigurationNode$1,
+ isParenGroupNode: isParenGroupNode$1
};
-var lineColumnToIndex = function (lineColumn, text) {
+var lineColumnToIndex$1 = function (lineColumn, text) {
let index = 0;
for (let i = 0; i < lineColumn.line - 1; ++i) {
@@ -48382,10 +50906,11 @@ var lineColumnToIndex = function (lineColumn, text) {
return index + lineColumn.column;
};
+const lineColumnToIndex = lineColumnToIndex$1;
const {
- getLast: getLast$a,
- skipEverythingButNewLine: skipEverythingButNewLine$2
-} = util;
+ getLast: getLast$8,
+ skipEverythingButNewLine
+} = util$8;
function calculateLocStart(node, text) {
// value-* nodes have this
@@ -48398,10 +50923,10 @@ function calculateLocStart(node, text) {
function calculateLocEnd(node, text) {
if (node.type === "css-comment" && node.inline) {
- return skipEverythingButNewLine$2(text, node.source.startOffset);
+ return skipEverythingButNewLine(text, node.source.startOffset);
}
- const endNode = node.nodes && getLast$a(node.nodes);
+ const endNode = node.nodes && getLast$8(node.nodes);
if (endNode && node.source && !node.source.end) {
node = endNode;
@@ -48605,105 +51130,112 @@ function replaceQuotesInInlineComments(text) {
return text;
}
-function locStart$9(node) {
+function locStart$e(node) {
return node.source.startOffset;
}
-function locEnd$f(node) {
+function locEnd$d(node) {
return node.source.endOffset;
}
-var loc$1 = {
- locStart: locStart$9,
- locEnd: locEnd$f,
+var loc$5 = {
+ locStart: locStart$e,
+ locEnd: locEnd$d,
calculateLoc,
replaceQuotesInInlineComments
};
+const getLast$7 = getLast_1;
const {
- printNumber: printNumber$3,
- printString: printString$3,
- hasNewline: hasNewline$8,
- isFrontMatterNode: isFrontMatterNode$2,
- isNextLineEmpty: isNextLineEmpty$a
-} = util;
+ printNumber,
+ printString,
+ hasNewline,
+ isFrontMatterNode: isFrontMatterNode$3,
+ isNextLineEmpty: isNextLineEmpty$3,
+ isNonEmptyArray: isNonEmptyArray$5
+} = util$8;
const {
builders: {
- concat: concat$B,
- join: join$h,
- line: line$k,
- hardline: hardline$o,
- softline: softline$i,
- group: group$p,
- fill: fill$4,
- indent: indent$r,
+ join: join$a,
+ line: line$d,
+ hardline: hardline$c,
+ softline: softline$9,
+ group: group$b,
+ fill: fill$6,
+ indent: indent$6,
dedent: dedent$2,
- ifBreak: ifBreak$e,
+ ifBreak: ifBreak$8,
breakParent: breakParent$5
},
utils: {
- removeLines: removeLines$2
+ removeLines,
+ getDocParts: getDocParts$5
}
-} = document;
+} = require$$7$3;
+const clean$8 = clean_1$3;
+const embed$7 = embed_1$3;
const {
- insertPragma: insertPragma$3
-} = pragma$1;
+ insertPragma: insertPragma$7
+} = pragma$4;
const {
getAncestorNode: getAncestorNode$1,
- getPropOfDeclNode: getPropOfDeclNode$1,
- maybeToLowerCase: maybeToLowerCase$1,
- insideValueFunctionNode: insideValueFunctionNode$1,
- insideICSSRuleNode: insideICSSRuleNode$1,
- insideAtRuleNode: insideAtRuleNode$1,
- insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
- isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
- isWideKeywords: isWideKeywords$1,
- isSCSS: isSCSS$1,
- isLastNode: isLastNode$1,
- isLessParser: isLessParser$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,
- isMathOperatorNode: isMathOperatorNode$1,
- isEachKeywordNode: isEachKeywordNode$1,
- isForKeywordNode: isForKeywordNode$1,
- isURLFunctionNode: isURLFunctionNode$1,
- isIfElseKeywordNode: isIfElseKeywordNode$1,
- hasComposesNode: hasComposesNode$1,
- hasParensAroundNode: hasParensAroundNode$1,
- hasEmptyRawBefore: hasEmptyRawBefore$1,
- isKeyValuePairNode: isKeyValuePairNode$1,
- isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
- isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
- isTemplatePropNode: isTemplatePropNode$1,
- isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
- 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,
- lastLineHasInlineComment: lastLineHasInlineComment$1,
- isAtWordPlaceholderNode: isAtWordPlaceholderNode$1
-} = utils$7;
+ getPropOfDeclNode,
+ maybeToLowerCase,
+ insideValueFunctionNode,
+ insideICSSRuleNode,
+ insideAtRuleNode,
+ insideURLFunctionInImportAtRuleNode,
+ isKeyframeAtRuleKeywords,
+ isWideKeywords,
+ isSCSS,
+ isLastNode,
+ isLessParser,
+ isSCSSControlDirectiveNode,
+ isDetachedRulesetDeclarationNode,
+ isRelationalOperatorNode,
+ isEqualityOperatorNode,
+ isMultiplicationNode,
+ isDivisionNode,
+ isAdditionNode,
+ isSubtractionNode,
+ isMathOperatorNode,
+ isEachKeywordNode,
+ isForKeywordNode,
+ isURLFunctionNode,
+ isIfElseKeywordNode,
+ hasComposesNode,
+ hasParensAroundNode,
+ hasEmptyRawBefore,
+ isKeyValuePairNode,
+ isKeyInValuePairNode,
+ isDetachedRulesetCallNode,
+ isTemplatePlaceholderNode,
+ isTemplatePropNode,
+ isPostcssSimpleVarNode,
+ isSCSSMapItemNode,
+ isInlineValueCommentNode,
+ isHashNode,
+ isLeftCurlyBraceNode,
+ isRightCurlyBraceNode,
+ isWordNode,
+ isColonNode,
+ isMediaAndSupportsKeywords,
+ isColorAdjusterFuncNode,
+ lastLineHasInlineComment,
+ isAtWordPlaceholderNode,
+ isConfigurationNode,
+ isParenGroupNode
+} = utils$4;
const {
- locStart: locStart$a,
- locEnd: locEnd$g
-} = loc$1;
+ locStart: locStart$d,
+ locEnd: locEnd$c
+} = loc$5;
-function shouldPrintComma$9(options) {
+function shouldPrintComma(options) {
return options.trailingComma === "es5" || options.trailingComma === "all";
}
-function genericPrint$2(path, options, print) {
+function genericPrint$4(path, options, print) {
const node = path.getValue();
/* istanbul ignore if */
@@ -48717,25 +51249,25 @@ function genericPrint$2(path, options, print) {
switch (node.type) {
case "front-matter":
- return concat$B([node.raw, hardline$o]);
+ return [node.raw, hardline$c];
case "css-root":
{
const nodes = printNodeSequence(path, options, print);
const after = node.raws.after.trim();
- return concat$B([nodes, after ? ` ${after}` : "", nodes.parts.length ? hardline$o : ""]);
+ return [nodes, after ? ` ${after}` : "", getDocParts$5(nodes).length > 0 ? hardline$c : ""];
}
case "css-comment":
{
const isInlineComment = node.inline || node.raws.inline;
- const text = options.originalText.slice(locStart$a(node), locEnd$g(node));
+ const text = options.originalText.slice(locStart$d(node), locEnd$c(node));
return isInlineComment ? text.trimEnd() : text;
}
case "css-rule":
{
- return concat$B([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$B([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$k : " ", "{", node.nodes.length > 0 ? indent$r(concat$B([hardline$o, printNodeSequence(path, options, print)])) : "", hardline$o, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
+ return [print("selector"), node.important ? " !important" : "", node.nodes ? [node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment(node.selector.value) ? line$d : " ", "{", node.nodes.length > 0 ? indent$6([hardline$c, printNodeSequence(path, options, print)]) : "", hardline$c, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""] : ";"];
}
case "css-decl":
@@ -48746,38 +51278,38 @@ function genericPrint$2(path, options, print) {
} = node.raws;
const trimmedBetween = rawBetween.trim();
const isColon = trimmedBetween === ":";
- let value = hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value");
+ let value = hasComposesNode(node) ? removeLines(print("value")) : print("value");
- if (!isColon && lastLineHasInlineComment$1(trimmedBetween)) {
- value = indent$r(concat$B([hardline$o, dedent$2(value)]));
+ if (!isColon && lastLineHasInlineComment(trimmedBetween)) {
+ value = indent$6([hardline$c, dedent$2(value)]);
}
- return concat$B([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser$1(options) && node.extend && node.selector ? concat$B(["extend(", path.call(print, "selector"), ")"]) : "", 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$B([" {", indent$r(concat$B([softline$i, printNodeSequence(path, options, print)])), softline$i, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[locEnd$g(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode$1(path, node) ? ifBreak$e(";", "") : ";"]);
+ return [node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path) ? node.prop : maybeToLowerCase(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser(options) && node.extend && node.selector ? ["extend(", print("selector"), ")"] : "", 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 ? [" {", indent$6([softline$9, printNodeSequence(path, options, print)]), softline$9, "}"] : isTemplatePropNode(node) && !parentNode.raws.semicolon && options.originalText[locEnd$c(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode(path, node) ? ifBreak$8(";") : ";"];
}
case "css-atrule":
{
const parentNode = path.getParentNode();
- const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[locEnd$g(node) - 1] !== ";";
+ const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode(node) && !parentNode.raws.semicolon && options.originalText[locEnd$c(node) - 1] !== ";";
- if (isLessParser$1(options)) {
+ if (isLessParser(options)) {
if (node.mixin) {
- return concat$B([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
+ return [print("selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
if (node.function) {
- return concat$B([node.name, concat$B([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
+ return [node.name, print("params"), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
if (node.variable) {
- return concat$B(["@", node.name, ": ", node.value ? concat$B([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$B(["{", indent$r(concat$B([node.nodes.length > 0 ? softline$i : "", printNodeSequence(path, options, print)])), softline$i, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
+ return ["@", node.name, ": ", node.value ? print("value") : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? ["{", indent$6([node.nodes.length > 0 ? softline$9 : "", printNodeSequence(path, options, print)]), softline$9, "}"] : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
}
- return concat$B(["@", // If a Less file ends up being parsed with the SCSS parser, Less
+ return ["@", // 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$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$B([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$B([hardline$o, hardline$o]) : /^\s*\n/.test(node.raws.afterName) ? hardline$o : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$r(concat$B([" ", path.call(print, "selector")])) : "", node.value ? group$p(concat$B([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$k : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$B([isSCSSControlDirectiveNode$1(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment$1(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment$1(node.params) ? line$k : " ", "{", indent$r(concat$B([node.nodes.length > 0 ? softline$i : "", printNodeSequence(path, options, print)])), softline$i, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
+ isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? [isDetachedRulesetCallNode(node) ? "" : isTemplatePlaceholderNode(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? [hardline$c, hardline$c] : /^\s*\n/.test(node.raws.afterName) ? hardline$c : " " : " ", print("params")] : "", node.selector ? indent$6([" ", print("selector")]) : "", node.value ? group$b([" ", print("value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$d : ""]) : node.name === "else" ? " " : "", node.nodes ? [isSCSSControlDirectiveNode(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment(node.params) ? line$d : " ", "{", indent$6([node.nodes.length > 0 ? softline$9 : "", printNodeSequence(path, options, print)]), softline$9, "}"] : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
// postcss-media-query-parser
@@ -48791,14 +51323,14 @@ function genericPrint$2(path, options, print) {
return;
}
- parts.push(childPath.call(print));
+ parts.push(print());
}, "nodes");
- return group$p(indent$r(join$h(line$k, parts)));
+ return group$b(indent$6(join$a(line$d, parts)));
}
case "media-query":
{
- return concat$B([join$h(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
+ return [join$a(" ", path.map(print, "nodes")), isLastNode(path, node) ? "" : ","];
}
case "media-type":
@@ -48812,17 +51344,17 @@ function genericPrint$2(path, options, print) {
return node.value;
}
- return concat$B(["(", concat$B(path.map(print, "nodes")), ")"]);
+ return ["(", ...path.map(print, "nodes"), ")"];
}
case "media-feature":
{
- return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
+ return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options));
}
case "media-colon":
{
- return concat$B([node.value, " "]);
+ return [node.value, " "];
}
case "media-value":
@@ -48837,7 +51369,7 @@ function genericPrint$2(path, options, print) {
case "media-url":
{
- return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
+ return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/g, ")"), options);
}
case "media-unknown":
@@ -48848,12 +51380,12 @@ function genericPrint$2(path, options, print) {
case "selector-root":
{
- return group$p(concat$B([insideAtRuleNode$1(path, "custom-selector") ? concat$B([getAncestorNode$1(path, "css-atrule").customSelector, line$k]) : "", join$h(concat$B([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$k : hardline$o]), path.map(print, "nodes"))]));
+ return group$b([insideAtRuleNode(path, "custom-selector") ? [getAncestorNode$1(path, "css-atrule").customSelector, line$d] : "", join$a([",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line$d : hardline$c], path.map(print, "nodes"))]);
}
case "selector-selector":
{
- return group$p(indent$r(concat$B(path.map(print, "nodes"))));
+ return group$b(indent$6(path.map(print, "nodes")));
}
case "selector-comment":
@@ -48871,45 +51403,45 @@ function genericPrint$2(path, options, print) {
const parentNode = path.getParentNode();
const index = parentNode && parentNode.nodes.indexOf(node);
const prevNode = index && parentNode.nodes[index - 1];
- return concat$B([node.namespace ? concat$B([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
+ return [node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value)];
}
case "selector-id":
{
- return concat$B(["#", node.value]);
+ return ["#", node.value];
}
case "selector-class":
{
- return concat$B([".", adjustNumbers(adjustStrings(node.value, options))]);
+ return [".", adjustNumbers(adjustStrings(node.value, options))];
}
case "selector-attribute":
{
- return concat$B(["[", node.namespace ? concat$B([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" : "", "]"]);
+ return ["[", node.namespace ? [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 === ">>>") {
const parentNode = path.getParentNode();
- const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$k;
- return concat$B([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
+ const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$d;
+ return [leading, node.value, isLastNode(path, node) ? "" : " "];
}
- const leading = node.value.trim().startsWith("(") ? line$k : "";
- const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$k;
- return concat$B([leading, value]);
+ const leading = node.value.trim().startsWith("(") ? line$d : "";
+ const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$d;
+ return [leading, value];
}
case "selector-universal":
{
- return concat$B([node.namespace ? concat$B([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
+ return [node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", node.value];
}
case "selector-pseudo":
{
- return concat$B([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$B(["(", join$h(", ", path.map(print, "nodes")), ")"]) : ""]);
+ return [maybeToLowerCase(node.value), isNonEmptyArray$5(node.nodes) ? ["(", join$a(", ", path.map(print, "nodes")), ")"] : ""];
}
case "selector-nesting":
@@ -48922,14 +51454,14 @@ function genericPrint$2(path, options, print) {
const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
- return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
+ return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options));
} // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
const parentNode = path.getParentNode();
if (parentNode.raws && parentNode.raws.selector) {
- const start = locStart$a(parentNode);
+ const start = locStart$d(parentNode);
const end = start + parentNode.raws.selector.length;
return options.originalText.slice(start, end).trim();
} // Same reason above
@@ -48938,10 +51470,10 @@ function genericPrint$2(path, options, print) {
const grandParent = path.getParentNode(1);
if (parentNode.type === "value-paren_group" && grandParent && grandParent.type === "value-func" && grandParent.value === "selector") {
- const start = locStart$a(parentNode.open) + 1;
- const end = locEnd$g(parentNode.close) - 1;
+ const start = locStart$d(parentNode.open) + 1;
+ const end = locEnd$c(parentNode.close) - 1;
const selector = options.originalText.slice(start, end).trim();
- return lastLineHasInlineComment$1(selector) ? concat$B([breakParent$5, selector]) : selector;
+ return lastLineHasInlineComment(selector) ? [breakParent$5, selector] : selector;
}
return node.value;
@@ -48951,25 +51483,26 @@ function genericPrint$2(path, options, print) {
case "value-value":
case "value-root":
{
- return path.call(print, "group");
+ return print("group");
}
case "value-comment":
{
- return options.originalText.slice(locStart$a(node), locEnd$g(node));
+ return options.originalText.slice(locStart$d(node), locEnd$c(node));
}
case "value-comma_group":
{
const parentNode = path.getParentNode();
const parentParentNode = path.getParentNode(1);
- const declAncestorProp = getPropOfDeclNode$1(path);
+ const declAncestorProp = getPropOfDeclNode(path);
const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
- const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
+ const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode);
+ const hasInlineComment = node.groups.some(node => isInlineValueCommentNode(node));
const printed = path.map(print, "groups");
const parts = [];
- const insideURLFunction = insideValueFunctionNode$1(path, "url");
+ const insideURLFunction = insideValueFunctionNode(path, "url");
let insideSCSSInterpolationInString = false;
let didBreak = false;
@@ -48981,10 +51514,15 @@ function genericPrint$2(path, options, print) {
const iNextNextNode = node.groups[i + 2];
if (insideURLFunction) {
- if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
+ if (iNextNode && isAdditionNode(iNextNode) || isAdditionNode(iNode)) {
parts.push(" ");
}
+ continue;
+ } // Ignore SCSS @forward wildcard suffix
+
+
+ if (insideAtRuleNode(path, "forward") && iNode.type === "value-word" && iNode.value && iPrevNode !== undefined && iPrevNode.type === "value-word" && iPrevNode.value === "as" && iNextNode.type === "value-operator" && iNextNode.value === "*") {
continue;
} // Ignore after latest node (i.e. before semicolon)
@@ -48994,7 +51532,7 @@ function genericPrint$2(path, options, print) {
} // styled.div` background: var(--${one}); `
- if (iNode.type === "value-word" && iNode.value.endsWith("-") && isAtWordPlaceholderNode$1(iNextNode)) {
+ if (iNode.type === "value-word" && iNode.value.endsWith("-") && isAtWordPlaceholderNode(iNextNode)) {
continue;
} // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
@@ -49012,7 +51550,7 @@ function genericPrint$2(path, options, print) {
} // Ignore colon (i.e. `:`)
- if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
+ if (isColonNode(iNode) || isColonNode(iNextNode)) {
continue;
} // Ignore `@` in Less (i.e. `@@var;`)
@@ -49042,60 +51580,67 @@ function genericPrint$2(path, options, print) {
} // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
- if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
+ if (isPostcssSimpleVarNode(iNode, iNextNode)) {
continue;
} // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
- if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
+ 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$1(iNextNode)) {
+ if (iNode.value === "--" && isHashNode(iNextNode)) {
continue;
} // Formatting math operations
- const isMathOperator = isMathOperatorNode$1(iNode);
- const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
+ const isMathOperator = isMathOperatorNode(iNode);
+ const 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$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
+ if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) {
+ continue;
+ } // absolute paths are only parsed as one token if they are part of url(/abs/path) call
+ // but if you have custom -fb-url(/abs/path/) then it is parsed as "division /" and rest
+ // of the path. We don't want to put a space after that first division in this case.
+
+
+ if (!iPrevNode && isDivisionNode(iNode)) {
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$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
+ if (insideValueFunctionNode(path, "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.
- const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
- const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
- const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
+ const isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode);
+ const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode);
+ const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign
- if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) {
+ if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path, "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;
} // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
- if (isInlineValueCommentNode$1(iNode)) {
+ if (isInlineValueCommentNode(iNode)) {
if (parentNode.type === "value-paren_group") {
- parts.push(dedent$2(hardline$o));
+ parts.push(dedent$2(hardline$c));
continue;
}
- parts.push(hardline$o);
+ parts.push(hardline$c);
continue;
} // Handle keywords in SCSS control directive
- if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
+ if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) {
parts.push(" ");
continue;
} // At-rule `namespace` should be in one line
@@ -49109,7 +51654,7 @@ function genericPrint$2(path, options, print) {
if (isGridValue) {
if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
- parts.push(hardline$o);
+ parts.push(hardline$c);
didBreak = true;
} else {
parts.push(" ");
@@ -49131,39 +51676,53 @@ function genericPrint$2(path, options, print) {
continue;
}
- if (isAtWordPlaceholderNode$1(iNode) && isAtWordPlaceholderNode$1(iNextNode) && locEnd$g(iNode) === locStart$a(iNextNode)) {
+ if (isAtWordPlaceholderNode(iNode) && isAtWordPlaceholderNode(iNextNode) && locEnd$c(iNode) === locStart$d(iNextNode)) {
+ continue;
+ }
+
+ if (isAtWordPlaceholderNode(iNode) && isParenGroupNode(iNextNode) && locEnd$c(iNode) === locStart$d(iNextNode.open)) {
+ parts.push(softline$9);
+ continue;
+ }
+
+ if (iNode.value === "with" && isParenGroupNode(iNextNode)) {
+ parts.push(" ");
continue;
} // Be default all values go through `line`
- parts.push(line$k);
+ parts.push(line$d);
+ }
+
+ if (hasInlineComment) {
+ parts.push(breakParent$5);
}
if (didBreak) {
- parts.unshift(hardline$o);
+ parts.unshift(hardline$c);
}
if (isControlDirective) {
- return group$p(indent$r(concat$B(parts)));
+ return group$b(indent$6(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$1(path)) {
- return group$p(fill$4(parts));
+ if (insideURLFunctionInImportAtRuleNode(path)) {
+ return group$b(fill$6(parts));
}
- return group$p(indent$r(fill$4(parts)));
+ return group$b(indent$6(fill$6(parts)));
}
case "value-paren_group":
{
const parentNode = path.getParentNode();
- if (parentNode && isURLFunctionNode$1(parentNode) && (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$B([node.open ? path.call(print, "open") : "", join$h(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
+ if (parentNode && isURLFunctionNode(parentNode) && (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 [node.open ? print("open") : "", join$a(",", path.map(print, "groups")), node.close ? print("close") : ""];
}
if (!node.open) {
@@ -49172,36 +51731,42 @@ function genericPrint$2(path, options, print) {
for (let i = 0; i < printed.length; i++) {
if (i !== 0) {
- res.push(concat$B([",", line$k]));
+ res.push([",", line$d]);
}
res.push(printed[i]);
}
- return group$p(indent$r(fill$4(res)));
+ return group$b(indent$6(fill$6(res)));
}
- const isSCSSMapItem = isSCSSMapItemNode$1(path);
- const lastItem = node.groups[node.groups.length - 1];
+ const isSCSSMapItem = isSCSSMapItemNode(path);
+ const lastItem = getLast$7(node.groups);
const isLastItemComment = lastItem && lastItem.type === "value-comment";
- return group$p(concat$B([node.open ? path.call(print, "open") : "", indent$r(concat$B([softline$i, join$h(concat$B([",", line$k]), path.map(childPath => {
+ const isKey = isKeyInValuePairNode(node, parentNode);
+ const isConfiguration = isConfigurationNode(node, parentNode);
+ const shouldBreak = isConfiguration || isSCSSMapItem && !isKey;
+ const shouldDedent = isConfiguration || isKey;
+ const printed = group$b([node.open ? print("open") : "", indent$6([softline$9, join$a([",", line$d], path.map(childPath => {
const node = childPath.getValue();
- const printed = print(childPath); // Key/Value pair in open paren already indented
+ const printed = print(); // Key/Value pair in open paren already indented
- if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
- printed.contents.contents.parts[1] = group$p(printed.contents.contents.parts[1]);
- return group$p(dedent$2(printed));
+ if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[0].type !== "value-paren_group" && node.groups[2] && node.groups[2].type === "value-paren_group") {
+ const parts = getDocParts$5(printed.contents.contents);
+ parts[1] = group$b(parts[1]);
+ return group$b(dedent$2(printed));
}
return printed;
- }, "groups"))])), ifBreak$e(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$9(options) ? "," : ""), softline$i, node.close ? path.call(print, "close") : ""]), {
- shouldBreak: isSCSSMapItem
+ }, "groups"))]), ifBreak$8(!isLastItemComment && isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$9, node.close ? print("close") : ""], {
+ shouldBreak
});
+ return shouldDedent ? dedent$2(printed) : printed;
}
case "value-func":
{
- return concat$B([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
+ return [node.value, insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", print("group")];
}
case "value-paren":
@@ -49211,7 +51776,7 @@ function genericPrint$2(path, options, print) {
case "value-number":
{
- return concat$B([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
+ return [printCssNumber(node.value), maybeToLowerCase(node.unit)];
}
case "value-operator":
@@ -49221,7 +51786,7 @@ function genericPrint$2(path, options, print) {
case "value-word":
{
- if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
+ if (node.isColor && node.isHex || isWideKeywords(node.value)) {
return node.value.toLowerCase();
}
@@ -49233,9 +51798,9 @@ function genericPrint$2(path, options, print) {
const parentNode = path.getParentNode();
const index = parentNode && parentNode.groups.indexOf(node);
const prevNode = index && parentNode.groups[index - 1];
- return concat$B([node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto;
- prevNode && prevNode.value[prevNode.value.length - 1] === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
- insideValueFunctionNode$1(path, "url") ? "" : line$k]);
+ return [node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto;
+ prevNode && typeof prevNode.value === "string" && getLast$7(prevNode.value) === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
+ insideValueFunctionNode(path, "url") ? "" : line$d];
}
// TODO: confirm this code is dead
@@ -49243,17 +51808,17 @@ function genericPrint$2(path, options, print) {
case "value-comma":
{
- return concat$B([node.value, " "]);
+ return [node.value, " "];
}
case "value-string":
{
- return printString$3(node.raws.quote + node.value + node.raws.quote, options);
+ return printString(node.raws.quote + node.value + node.raws.quote, options);
}
case "value-atword":
{
- return concat$B(["@", node.value]);
+ return ["@", node.value];
}
case "value-unicode-range":
@@ -49273,43 +51838,42 @@ function genericPrint$2(path, options, print) {
}
function printNodeSequence(path, options, print) {
- const node = path.getValue();
const parts = [];
- path.each((pathChild, i) => {
- const prevNode = node.nodes[i - 1];
+ path.each((pathChild, i, nodes) => {
+ const prevNode = nodes[i - 1];
if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
const childNode = pathChild.getValue();
- parts.push(options.originalText.slice(locStart$a(childNode), locEnd$g(childNode)));
+ parts.push(options.originalText.slice(locStart$d(childNode), locEnd$c(childNode)));
} else {
- parts.push(pathChild.call(print));
+ parts.push(print());
}
- if (i !== node.nodes.length - 1) {
- if (node.nodes[i + 1].type === "css-comment" && !hasNewline$8(options.originalText, locStart$a(node.nodes[i + 1]), {
+ if (i !== nodes.length - 1) {
+ if (nodes[i + 1].type === "css-comment" && !hasNewline(options.originalText, locStart$d(nodes[i + 1]), {
backwards: true
- }) && !isFrontMatterNode$2(node.nodes[i]) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
+ }) && !isFrontMatterNode$3(nodes[i]) || nodes[i + 1].type === "css-atrule" && nodes[i + 1].name === "else" && nodes[i].type !== "css-comment") {
parts.push(" ");
} else {
- parts.push(options.__isHTMLStyleAttribute ? line$k : hardline$o);
+ parts.push(options.__isHTMLStyleAttribute ? line$d : hardline$c);
- if (isNextLineEmpty$a(options.originalText, pathChild.getValue(), locEnd$g) && !isFrontMatterNode$2(node.nodes[i])) {
- parts.push(hardline$o);
+ if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), locEnd$c) && !isFrontMatterNode$3(nodes[i])) {
+ parts.push(hardline$c);
}
}
}
}, "nodes");
- return concat$B(parts);
+ return parts;
}
-const STRING_REGEX$3 = /(["'])(?:(?!\1)[^\\]|\\[\S\s])*\1/g;
+const STRING_REGEX = /(["'])(?:(?!\1)[^\\]|\\.)*\1/gs;
const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[Ee][+-]?\d+)?/g;
const STANDARD_UNIT_REGEX = /[A-Za-z]+/g;
const WORD_PART_REGEX = /[$@]?[A-Z_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/g;
-const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
+const ADJUST_NUMBERS_REGEX = new 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$3, match => printString$3(match, options));
+ return value.replace(STRING_REGEX, match => printString(match, options));
}
function quoteAttributeValue(value, options) {
@@ -49318,176 +51882,183 @@ function quoteAttributeValue(value, options) {
}
function adjustNumbers(value) {
- return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
+ return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase(unit || "") : match);
}
function printCssNumber(rawNumber) {
- return printNumber$3(rawNumber) // Remove trailing `.0`.
+ return printNumber(rawNumber) // Remove trailing `.0`.
.replace(/\.0(?=$|e)/, "");
}
var printerPostcss = {
- print: genericPrint$2,
- embed: embed_1$1,
- insertPragma: insertPragma$3,
- massageAstNode: clean_1$1
+ print: genericPrint$4,
+ embed: embed$7,
+ insertPragma: insertPragma$7,
+ massageAstNode: clean$8
};
-var options$3 = {
- singleQuote: commonOptions.singleQuote
+const commonOptions$4 = commonOptions$6; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
+
+var options$9 = {
+ singleQuote: commonOptions$4.singleQuote
+};
+
+var parsers$b = {
+ // TODO: switch these to just `postcss` and use `language` instead.
+ get css() {
+ return require("./parser-postcss.js").parsers.css;
+ },
+
+ get less() {
+ return require("./parser-postcss.js").parsers.less;
+ },
+
+ get scss() {
+ return require("./parser-postcss.js").parsers.scss;
+ }
+
};
var name$9 = "CSS";
-var type$7 = "markup";
-var tmScope$7 = "source.css";
-var aceMode$7 = "css";
-var codemirrorMode$7 = "css";
-var codemirrorMimeType$7 = "text/css";
-var color$2 = "#563d7c";
-var extensions$7 = [
+var type$9 = "markup";
+var tmScope$9 = "source.css";
+var aceMode$9 = "css";
+var codemirrorMode$5 = "css";
+var codemirrorMimeType$5 = "text/css";
+var color$8 = "#563d7c";
+var extensions$9 = [
".css"
];
-var languageId$7 = 50;
-var require$$0$3 = {
+var languageId$9 = 50;
+var require$$4$5 = {
name: name$9,
- type: type$7,
- tmScope: tmScope$7,
- aceMode: aceMode$7,
- codemirrorMode: codemirrorMode$7,
- codemirrorMimeType: codemirrorMimeType$7,
- color: color$2,
- extensions: extensions$7,
- languageId: languageId$7
+ type: type$9,
+ tmScope: tmScope$9,
+ aceMode: aceMode$9,
+ codemirrorMode: codemirrorMode$5,
+ codemirrorMimeType: codemirrorMimeType$5,
+ color: color$8,
+ extensions: extensions$9,
+ languageId: languageId$9
};
-var name$a = "PostCSS";
+var name$8 = "PostCSS";
var type$8 = "markup";
var tmScope$8 = "source.postcss";
-var group$q = "CSS";
+var group$a = "CSS";
var extensions$8 = [
".pcss",
".postcss"
];
var aceMode$8 = "text";
var languageId$8 = 262764437;
-var require$$1$1 = {
- name: name$a,
+var require$$5$1 = {
+ name: name$8,
type: type$8,
tmScope: tmScope$8,
- group: group$q,
+ group: group$a,
extensions: extensions$8,
aceMode: aceMode$8,
languageId: languageId$8
};
-var name$b = "Less";
-var type$9 = "markup";
-var color$3 = "#1d365d";
-var extensions$9 = [
+var name$7 = "Less";
+var type$7 = "markup";
+var color$7 = "#1d365d";
+var extensions$7 = [
".less"
];
-var tmScope$9 = "source.css.less";
-var aceMode$9 = "less";
-var codemirrorMode$8 = "css";
-var codemirrorMimeType$8 = "text/css";
-var languageId$9 = 198;
-var require$$2$1 = {
- name: name$b,
- type: type$9,
- color: color$3,
- extensions: extensions$9,
- tmScope: tmScope$9,
- aceMode: aceMode$9,
- codemirrorMode: codemirrorMode$8,
- codemirrorMimeType: codemirrorMimeType$8,
- languageId: languageId$9
+var tmScope$7 = "source.css.less";
+var aceMode$7 = "less";
+var codemirrorMode$4 = "css";
+var codemirrorMimeType$4 = "text/css";
+var languageId$7 = 198;
+var require$$6 = {
+ name: name$7,
+ type: type$7,
+ color: color$7,
+ extensions: extensions$7,
+ tmScope: tmScope$7,
+ aceMode: aceMode$7,
+ codemirrorMode: codemirrorMode$4,
+ codemirrorMimeType: codemirrorMimeType$4,
+ languageId: languageId$7
};
-var name$c = "SCSS";
-var type$a = "markup";
-var color$4 = "#c6538c";
-var tmScope$a = "source.css.scss";
-var aceMode$a = "scss";
-var codemirrorMode$9 = "css";
-var codemirrorMimeType$9 = "text/x-scss";
-var extensions$a = [
+var name$6 = "SCSS";
+var type$6 = "markup";
+var color$6 = "#c6538c";
+var tmScope$6 = "source.css.scss";
+var aceMode$6 = "scss";
+var codemirrorMode$3 = "css";
+var codemirrorMimeType$3 = "text/x-scss";
+var extensions$6 = [
".scss"
];
-var languageId$a = 329;
-var require$$3$1 = {
- name: name$c,
- type: type$a,
- color: color$4,
- tmScope: tmScope$a,
- aceMode: aceMode$a,
- codemirrorMode: codemirrorMode$9,
- codemirrorMimeType: codemirrorMimeType$9,
- extensions: extensions$a,
- languageId: languageId$a
+var languageId$6 = 329;
+var require$$7 = {
+ name: name$6,
+ type: type$6,
+ color: color$6,
+ tmScope: tmScope$6,
+ aceMode: aceMode$6,
+ codemirrorMode: codemirrorMode$3,
+ codemirrorMimeType: codemirrorMimeType$3,
+ extensions: extensions$6,
+ languageId: languageId$6
};
-const languages$1 = [createLanguage(require$$0$3, data => ({
+const createLanguage$5 = createLanguage$7;
+const printer$5 = printerPostcss;
+const options$8 = options$9;
+const parsers$a = parsers$b;
+const languages$6 = [createLanguage$5(require$$4$5, data => ({
since: "1.4.0",
parsers: ["css"],
vscodeLanguageIds: ["css"],
extensions: [...data.extensions, // `WeiXin Style Sheets`(Weixin Mini Programs)
// https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/
".wxss"]
-})), createLanguage(require$$1$1, () => ({
+})), createLanguage$5(require$$5$1, () => ({
since: "1.4.0",
parsers: ["css"],
vscodeLanguageIds: ["postcss"]
-})), createLanguage(require$$2$1, () => ({
+})), createLanguage$5(require$$6, () => ({
since: "1.4.0",
parsers: ["less"],
vscodeLanguageIds: ["less"]
-})), createLanguage(require$$3$1, () => ({
+})), createLanguage$5(require$$7, () => ({
since: "1.4.0",
parsers: ["scss"],
vscodeLanguageIds: ["scss"]
}))];
-const printers$1 = {
- postcss: printerPostcss
-};
-const parsers$1 = {
- // 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.less;
- },
-
- get scss() {
- return require("./parser-postcss").parsers.scss;
- }
-
+const printers$4 = {
+ postcss: printer$5
};
var languageCss = {
- languages: languages$1,
- options: options$3,
- printers: printers$1,
- parsers: parsers$1
+ languages: languages$6,
+ options: options$8,
+ printers: printers$4,
+ parsers: parsers$a
};
-function locStart$b(node) {
+function locStart$c(node) {
return node.loc.start.offset;
}
-function locEnd$h(node) {
+function locEnd$b(node) {
return node.loc.end.offset;
}
-var loc$2 = {
- locStart: locStart$b,
- locEnd: locEnd$h
+var loc$4 = {
+ locStart: locStart$c,
+ locEnd: locEnd$b
};
-function clean$3(ast, newNode
+function clean$7(ast, newNode
/*, parent*/
) {
- // (Glimmer/HTML) ignore TextNode whitespace
+ // (Glimmer/HTML) ignore TextNode
if (ast.type === "TextNode") {
const trimmed = ast.chars.trim();
@@ -49495,14 +52066,19 @@ function clean$3(ast, newNode
return null;
}
- newNode.chars = trimmed;
+ newNode.chars = trimmed.replace(/[\t\n\f\r ]+/g, " ");
+ } // `class` is reformatted
+
+
+ if (ast.type === "AttrNode" && ast.name.toLowerCase() === "class") {
+ delete newNode.value;
}
}
-clean$3.ignoredProperties = new Set(["loc", "selfClosing"]);
-var clean_1$2 = clean$3;
+clean$7.ignoredProperties = new Set(["loc", "selfClosing"]);
+var clean_1$2 = clean$7;
-var htmlVoidElements = [
+var require$$0$1 = [
"area",
"base",
"basefont",
@@ -49528,41 +52104,59 @@ var htmlVoidElements = [
"wbr"
];
+const htmlVoidElements = require$$0$1;
+const getLast$6 = getLast_1;
+
+function isLastNodeOfSiblings$1(path) {
+ const node = path.getValue();
+ const parentNode = path.getParentNode(0);
+
+ if (isParentOfSomeType$1(path, ["ElementNode"]) && getLast$6(parentNode.children) === node) {
+ return true;
+ }
+
+ if (isParentOfSomeType$1(path, ["Block"]) && getLast$6(parentNode.body) === node) {
+ return true;
+ }
+
+ return false;
+}
+
function isUppercase(string) {
return string.toUpperCase() === string;
}
function isGlimmerComponent(node) {
- return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
+ return isNodeOfSomeType$1(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
}
const voidTags = new Set(htmlVoidElements);
-function isVoid(node) {
- return isGlimmerComponent(node) && node.children.every(n => isWhitespaceNode(n)) || voidTags.has(node.tag);
+function isVoid$1(node) {
+ return isGlimmerComponent(node) && node.children.every(node => isWhitespaceNode$1(node)) || voidTags.has(node.tag);
}
-function isWhitespaceNode(node) {
- return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
+function isWhitespaceNode$1(node) {
+ return isNodeOfSomeType$1(node, ["TextNode"]) && !/\S/.test(node.chars);
}
-function isNodeOfSomeType(node, types) {
- return node && types.some(type => node.type === type);
+function isNodeOfSomeType$1(node, types) {
+ return node && types.includes(node.type);
}
-function isParentOfSomeType(path, types) {
+function isParentOfSomeType$1(path, types) {
const parentNode = path.getParentNode(0);
- return isNodeOfSomeType(parentNode, types);
+ return isNodeOfSomeType$1(parentNode, types);
}
-function isPreviousNodeOfSomeType(path, types) {
- const previousNode = getPreviousNode(path);
- return isNodeOfSomeType(previousNode, types);
+function isPreviousNodeOfSomeType$1(path, types) {
+ const previousNode = getPreviousNode$1(path);
+ return isNodeOfSomeType$1(previousNode, types);
}
-function isNextNodeOfSomeType(path, types) {
- const nextNode = getNextNode(path);
- return isNodeOfSomeType(nextNode, types);
+function isNextNodeOfSomeType$1(path, types) {
+ const nextNode = getNextNode$1(path);
+ return isNodeOfSomeType$1(nextNode, types);
}
function getSiblingNode(path, offset) {
@@ -49573,220 +52167,312 @@ function getSiblingNode(path, offset) {
return index !== -1 && children[index + offset];
}
-function getPreviousNode(path, lookBack = 1) {
+function getPreviousNode$1(path, lookBack = 1) {
return getSiblingNode(path, -lookBack);
}
-function getNextNode(path) {
+function getNextNode$1(path) {
return getSiblingNode(path, 1);
}
function isPrettierIgnoreNode(node) {
- return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
+ return isNodeOfSomeType$1(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
}
-function hasPrettierIgnore$2(path) {
+function hasPrettierIgnore$8(path) {
const node = path.getValue();
- const previousPreviousNode = getPreviousNode(path, 2);
+ const previousPreviousNode = getPreviousNode$1(path, 2);
return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
}
-var utils$8 = {
- getNextNode,
- getPreviousNode,
- hasPrettierIgnore: hasPrettierIgnore$2,
- isNextNodeOfSomeType,
- isNodeOfSomeType,
- isParentOfSomeType,
- isPreviousNodeOfSomeType,
- isVoid,
- isWhitespaceNode
-};
-
-const {
- builders: {
- concat: concat$C,
- group: group$r,
- hardline: hardline$p,
- ifBreak: ifBreak$f,
- indent: indent$s,
- join: join$i,
- line: line$l,
- softline: softline$j
- }
-} = document;
-const {
- locStart: locStart$c,
- locEnd: locEnd$i
-} = loc$2;
-const {
+var utils$3 = {
getNextNode: getNextNode$1,
getPreviousNode: getPreviousNode$1,
- hasPrettierIgnore: hasPrettierIgnore$3,
+ hasPrettierIgnore: hasPrettierIgnore$8,
+ isLastNodeOfSiblings: isLastNodeOfSiblings$1,
isNextNodeOfSomeType: isNextNodeOfSomeType$1,
isNodeOfSomeType: isNodeOfSomeType$1,
isParentOfSomeType: isParentOfSomeType$1,
isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
isVoid: isVoid$1,
isWhitespaceNode: isWhitespaceNode$1
-} = utils$8; // Formatter based on @glimmerjs/syntax's built-in test formatter:
+};
+
+const {
+ builders: {
+ dedent: dedent$1,
+ fill: fill$5,
+ group: group$9,
+ hardline: hardline$b,
+ ifBreak: ifBreak$7,
+ indent: indent$5,
+ join: join$9,
+ line: line$c,
+ softline: softline$8
+ },
+ utils: {
+ getDocParts: getDocParts$4,
+ replaceTextEndOfLine: replaceTextEndOfLine$8
+ }
+} = require$$7$3;
+const {
+ getPreferredQuote,
+ isNonEmptyArray: isNonEmptyArray$4
+} = util$8;
+const {
+ locStart: locStart$b,
+ locEnd: locEnd$a
+} = loc$4;
+const clean$6 = clean_1$2;
+const {
+ getNextNode,
+ getPreviousNode,
+ hasPrettierIgnore: hasPrettierIgnore$7,
+ isLastNodeOfSiblings,
+ isNextNodeOfSomeType,
+ isNodeOfSomeType,
+ isParentOfSomeType,
+ isPreviousNodeOfSomeType,
+ isVoid,
+ isWhitespaceNode
+} = utils$3;
+const NEWLINES_TO_PRESERVE_MAX = 2; // 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$2(path, options, print) {
- const n = path.getValue();
+function print(path, options, print) {
+ const node = path.getValue();
/* istanbul ignore if*/
- if (!n) {
+ if (!node) {
return "";
}
- if (hasPrettierIgnore$3(path)) {
- return options.originalText.slice(locStart$c(n), locEnd$i(n));
+ if (hasPrettierIgnore$7(path)) {
+ return options.originalText.slice(locStart$b(node), locEnd$a(node));
}
- switch (n.type) {
+ const favoriteQuote = options.singleQuote ? "'" : '"';
+
+ switch (node.type) {
case "Block":
case "Program":
case "Template":
{
- return group$r(concat$C(path.map(print, "body")));
+ return group$9(path.map(print, "body"));
}
case "ElementNode":
{
- // TODO: make it whitespace sensitive
- const bim = isNextNodeOfSomeType$1(path, ["ElementNode"]) ? hardline$p : "";
+ const startingTag = group$9(printStartingTag(path, print));
+ const escapeNextElementNode = options.htmlWhitespaceSensitivity === "ignore" && isNextNodeOfSomeType(path, ["ElementNode"]) ? softline$8 : "";
+
+ if (isVoid(node)) {
+ return [startingTag, escapeNextElementNode];
+ }
+
+ const endingTag = ["", node.tag, ">"];
- if (isVoid$1(n)) {
- return concat$C([group$r(printStartingTag(path, print)), bim]);
+ if (node.children.length === 0) {
+ return [startingTag, indent$5(endingTag), escapeNextElementNode];
}
- const isWhitespaceOnly = n.children.every(n => isWhitespaceNode$1(n));
- return concat$C([group$r(printStartingTag(path, print)), group$r(concat$C([isWhitespaceOnly ? "" : indent$s(printChildren(path, options, print)), n.children.length ? hardline$p : "", concat$C(["", n.tag, ">"])])), bim]);
+ if (options.htmlWhitespaceSensitivity === "ignore") {
+ return [startingTag, indent$5(printChildren$5(path, options, print)), hardline$b, indent$5(endingTag), escapeNextElementNode];
+ }
+
+ return [startingTag, indent$5(group$9(printChildren$5(path, options, print))), indent$5(endingTag), escapeNextElementNode];
}
case "BlockStatement":
{
const pp = path.getParentNode(1);
- const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
+ const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === node && pp.inverse.body[0].path.parts[0] === "if";
if (isElseIf) {
- return concat$C([printElseIfBlock(path, print), printProgram(path, print), printInverse(path, print)]);
+ return [printElseIfBlock(path, print), printProgram(path, print, options), printInverse(path, print, options)];
}
- return concat$C([printOpenBlock(path, print), group$r(concat$C([printProgram(path, print), printInverse(path, print), printCloseBlock(path, print)]))]);
+ return [printOpenBlock(path, print), group$9([printProgram(path, print, options), printInverse(path, print, options), printCloseBlock(path, print, options)])];
}
case "ElementModifierStatement":
{
- return group$r(concat$C(["{{", printPathAndParams(path, print), softline$j, "}}"]));
+ return group$9(["{{", printPathAndParams(path, print), "}}"]);
}
case "MustacheStatement":
{
- const isParentOfSpecifiedTypes = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement"]);
- const isChildOfElementNodeAndDoesNotHaveParams = isParentOfSomeType$1(path, ["ElementNode"]) && doesNotHaveHashParams(n) && doesNotHavePositionalParams(n);
- const shouldBreakOpeningMustache = isParentOfSpecifiedTypes || isChildOfElementNodeAndDoesNotHaveParams;
- return group$r(concat$C([printOpeningMustache(n), shouldBreakOpeningMustache ? indent$s(softline$j) : "", printPathAndParams(path, print), softline$j, printClosingMustache(n)]));
+ return group$9([printOpeningMustache(node), printPathAndParams(path, print), printClosingMustache(node)]);
}
case "SubExpression":
{
- return group$r(concat$C(["(", printSubExpressionPathAndParams(path, print), softline$j, ")"]));
+ return group$9(["(", printSubExpressionPathAndParams(path, print), softline$8, ")"]);
}
case "AttrNode":
{
- const isText = n.value.type === "TextNode";
- const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end offsets are the
+ const isText = node.value.type === "TextNode";
+ const isEmptyText = isText && node.value.chars === ""; // If the text is empty and the value's loc start and end offsets are the
// same, there is no value for this AttrNode and it should be printed
// without the `=""`. Example: `` -> ``
- if (isEmptyText && locStart$c(n.value) === locEnd$i(n.value)) {
- return concat$C([n.name]);
- }
+ if (isEmptyText && locStart$b(node.value) === locEnd$a(node.value)) {
+ return node.name;
+ } // Let's assume quotes inside the content of text nodes are already
+ // properly escaped with entities, otherwise the parse wouldn't have parsed them.
- const value = path.call(print, "value");
- const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
- return concat$C([n.name, "=", quotedValue]);
+
+ const quote = isText ? getPreferredQuote(node.value.chars, favoriteQuote).quote : node.value.type === "ConcatStatement" ? getPreferredQuote(node.value.parts.filter(part => part.type === "TextNode").map(part => part.chars).join(""), favoriteQuote).quote : "";
+ const valueDoc = print("value");
+ return [node.name, "=", quote, node.name === "class" && quote ? group$9(indent$5(valueDoc)) : valueDoc, quote];
}
case "ConcatStatement":
{
- const quote = options.singleQuote ? "'" : '"';
- return concat$C([quote, ...path.map(partPath => print(partPath), "parts"), quote]);
+ return path.map(print, "parts");
}
case "Hash":
{
- return concat$C([join$i(line$l, path.map(print, "pairs"))]);
+ return join$9(line$c, path.map(print, "pairs"));
}
case "HashPair":
{
- return concat$C([n.key, "=", path.call(print, "value")]);
+ return [node.key, "=", print("value")];
}
case "TextNode":
{
- const maxLineBreaksToPreserve = 2;
- const isFirstElement = !getPreviousNode$1(path);
- const isLastElement = !getNextNode$1(path);
- const isWhitespaceOnly = !/\S/.test(n.chars);
- const lineBreaksCount = countNewLines(n.chars);
- let leadingLineBreaksCount = countLeadingNewLines(n.chars);
- let trailingLineBreaksCount = countTrailingNewLines(n.chars);
-
- if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType$1(path, ["Block", "ElementNode", "Template"])) {
- return "";
- }
+ /* if `{{my-component}}` (or any text containing "{{")
+ * makes it to the TextNode, it means it was escaped,
+ * so let's print it escaped, ie.; `\{{my-component}}` */
+ let text = node.chars.replace(/{{/g, "\\{{");
+ const attrName = getCurrentAttributeName(path);
- if (isWhitespaceOnly && lineBreaksCount) {
- leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
- trailingLineBreaksCount = 0;
- } else {
- if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
- trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
- }
+ if (attrName) {
+ // TODO: format style and srcset attributes
+ if (attrName === "class") {
+ const formattedClasses = text.trim().split(/\s+/).join(" ");
+ let leadingSpace = false;
+ let trailingSpace = false;
+
+ if (isParentOfSomeType(path, ["ConcatStatement"])) {
+ if (isPreviousNodeOfSomeType(path, ["MustacheStatement"]) && /^\s/.test(text)) {
+ leadingSpace = true;
+ }
- if (isPreviousNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
- leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
+ if (isNextNodeOfSomeType(path, ["MustacheStatement"]) && /\s$/.test(text) && formattedClasses !== "") {
+ trailingSpace = true;
+ }
+ }
+
+ return [leadingSpace ? line$c : "", formattedClasses, trailingSpace ? line$c : ""];
}
+
+ return replaceTextEndOfLine$8(text);
}
- const inAttrNode = path.stack.includes("attributes");
+ const whitespacesOnlyRE = /^[\t\n\f\r ]*$/;
+ const isWhitespaceOnly = whitespacesOnlyRE.test(text);
+ const isFirstElement = !getPreviousNode(path);
+ const isLastElement = !getNextNode(path);
- if (inAttrNode) {
- // TODO: format style and srcset attributes
- // and cleanup concat that is not necessary
- if (!isInAttributeOfName(path, "class")) {
- return concat$C([n.chars]);
+ if (options.htmlWhitespaceSensitivity !== "ignore") {
+ // https://infra.spec.whatwg.org/#ascii-whitespace
+ const leadingWhitespacesRE = /^[\t\n\f\r ]*/;
+ const trailingWhitespacesRE = /[\t\n\f\r ]*$/; // let's remove the file's final newline
+ // https://github.com/ember-cli/ember-new-output/blob/1a04c67ddd02ccb35e0ff41bb5cbce34b31173ef/.editorconfig#L16
+
+ const shouldTrimTrailingNewlines = isLastElement && isParentOfSomeType(path, ["Template"]);
+ const shouldTrimLeadingNewlines = isFirstElement && isParentOfSomeType(path, ["Template"]);
+
+ if (isWhitespaceOnly) {
+ if (shouldTrimLeadingNewlines || shouldTrimTrailingNewlines) {
+ return "";
+ }
+
+ let breaks = [line$c];
+ const newlines = countNewLines(text);
+
+ if (newlines) {
+ breaks = generateHardlines(newlines);
+ }
+
+ if (isLastNodeOfSiblings(path)) {
+ breaks = breaks.map(newline => dedent$1(newline));
+ }
+
+ return breaks;
}
- let leadingSpace = "";
- let trailingSpace = "";
+ const [lead] = text.match(leadingWhitespacesRE);
+ const [tail] = text.match(trailingWhitespacesRE);
+ let leadBreaks = [];
- if (isParentOfSomeType$1(path, ["ConcatStatement"])) {
- if (isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
- leadingSpace = " ";
+ if (lead) {
+ leadBreaks = [line$c];
+ const leadingNewlines = countNewLines(lead);
+
+ if (leadingNewlines) {
+ leadBreaks = generateHardlines(leadingNewlines);
}
- if (isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
- trailingSpace = " ";
+ text = text.replace(leadingWhitespacesRE, "");
+ }
+
+ let trailBreaks = [];
+
+ if (tail) {
+ if (!shouldTrimTrailingNewlines) {
+ trailBreaks = [line$c];
+ const trailingNewlines = countNewLines(tail);
+
+ if (trailingNewlines) {
+ trailBreaks = generateHardlines(trailingNewlines);
+ }
+
+ if (isLastNodeOfSiblings(path)) {
+ trailBreaks = trailBreaks.map(hardline => dedent$1(hardline));
+ }
}
+
+ text = text.replace(trailingWhitespacesRE, "");
+ }
+
+ return [...leadBreaks, fill$5(getTextValueParts$3(text)), ...trailBreaks];
+ }
+
+ const lineBreaksCount = countNewLines(text);
+ let leadingLineBreaksCount = countLeadingNewLines(text);
+ let trailingLineBreaksCount = countTrailingNewLines(text);
+
+ if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType(path, ["Block", "ElementNode", "Template"])) {
+ return "";
+ }
+
+ if (isWhitespaceOnly && lineBreaksCount) {
+ leadingLineBreaksCount = Math.min(lineBreaksCount, NEWLINES_TO_PRESERVE_MAX);
+ trailingLineBreaksCount = 0;
+ } else {
+ if (isNextNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
+ trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
}
- return concat$C([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
+ if (isPreviousNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
+ leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
+ }
}
let leadingSpace = "";
let trailingSpace = "";
- if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
+ if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType(path, ["MustacheStatement"])) {
trailingSpace = " ";
}
- if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
+ if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType(path, ["MustacheStatement"])) {
leadingSpace = " ";
}
@@ -49800,48 +52486,50 @@ function print$2(path, options, print) {
trailingSpace = "";
}
- let text = n.chars;
- /* if `{{my-component}}` (or any text starting with a mustache)
- * makes it to the TextNode,
- * it means it was escaped,
- * so let's print it escaped, ie.; `\{{my-component}}` */
-
- if (text.startsWith("{{") && text.includes("}}")) {
- text = "\\" + text;
- }
-
- return concat$C([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), text.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
+ text = text.replace(/^[\t\n\f\r ]+/g, leadingSpace).replace(/[\t\n\f\r ]+$/, trailingSpace);
+ return [...generateHardlines(leadingLineBreaksCount), fill$5(getTextValueParts$3(text)), ...generateHardlines(trailingLineBreaksCount)];
}
case "MustacheCommentStatement":
{
- const dashes = n.value.includes("}}") ? "--" : "";
- return concat$C(["{{!", dashes, n.value, dashes, "}}"]);
+ const start = locStart$b(node);
+ const end = locEnd$a(node); // Starts with `{{~`
+
+ const isLeftWhiteSpaceSensitive = options.originalText.charAt(start + 2) === "~"; // Ends with `{{~`
+
+ const isRightWhitespaceSensitive = options.originalText.charAt(end - 3) === "~";
+ const dashes = node.value.includes("}}") ? "--" : "";
+ return ["{{", isLeftWhiteSpaceSensitive ? "~" : "", "!", dashes, node.value, dashes, isRightWhitespaceSensitive ? "~" : "", "}}"];
}
case "PathExpression":
{
- return n.original;
+ return node.original;
}
case "BooleanLiteral":
{
- return String(n.value);
+ return String(node.value);
}
case "CommentStatement":
{
- return concat$C([""]);
+ return [""];
}
case "StringLiteral":
{
- return printStringLiteral(n.value, options);
+ if (needsOppositeQuote(path)) {
+ const printFavoriteQuote = !options.singleQuote ? "'" : '"';
+ return printStringLiteral(node.value, printFavoriteQuote);
+ }
+
+ return printStringLiteral(node.value, favoriteQuote);
}
case "NumberLiteral":
{
- return String(n.value);
+ return String(node.value);
}
case "UndefinedLiteral":
@@ -49857,38 +52545,60 @@ function print$2(path, options, print) {
/* istanbul ignore next */
default:
- throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
+ throw new Error("unknown glimmer type: " + JSON.stringify(node.type));
}
}
/* ElementNode print helpers */
+function sortByLoc(a, b) {
+ return locStart$b(a) - locStart$b(b);
+}
+
function printStartingTag(path, print) {
const node = path.getValue();
- return concat$C(["<", node.tag, printAttributesLike(path, print), printBlockParams(node), printStartingTagEndMarker(node)]);
+ const types = ["attributes", "modifiers", "comments"].filter(property => isNonEmptyArray$4(node[property]));
+ const attributes = types.flatMap(type => node[type]).sort(sortByLoc);
+
+ for (const attributeType of types) {
+ path.each(attributePath => {
+ const index = attributes.indexOf(attributePath.getValue());
+ attributes.splice(index, 1, [line$c, print()]);
+ }, attributeType);
+ }
+
+ if (isNonEmptyArray$4(node.blockParams)) {
+ attributes.push(line$c, printBlockParams(node));
+ }
+
+ return ["<", node.tag, indent$5(attributes), printStartingTagEndMarker(node)];
}
-function printAttributesLike(path, print) {
+function printChildren$5(path, options, print) {
const node = path.getValue();
- return indent$s(concat$C([node.attributes.length ? line$l : "", join$i(line$l, path.map(print, "attributes")), node.modifiers.length ? line$l : "", join$i(line$l, path.map(print, "modifiers")), node.comments.length ? line$l : "", join$i(line$l, path.map(print, "comments"))]));
-}
+ const isEmpty = node.children.every(node => isWhitespaceNode(node));
+
+ if (options.htmlWhitespaceSensitivity === "ignore" && isEmpty) {
+ return "";
+ }
+
+ return path.map((childPath, childIndex) => {
+ const printedChild = print();
-function printChildren(path, options, print) {
- return concat$C(path.map((childPath, childIndex) => {
- if (childIndex === 0) {
- return concat$C([softline$j, print(childPath, options, print)]);
+ if (childIndex === 0 && options.htmlWhitespaceSensitivity === "ignore") {
+ return [softline$8, printedChild];
}
- return print(childPath, options, print);
- }, "children"));
+ return printedChild;
+ }, "children");
}
function printStartingTagEndMarker(node) {
- if (isVoid$1(node)) {
- return ifBreak$f(concat$C([softline$j, "/>"]), concat$C([" />", softline$j]));
+ if (isVoid(node)) {
+ return ifBreak$7([softline$8, "/>"], [" />", softline$8]);
}
- return ifBreak$f(concat$C([softline$j, ">"]), ">");
+ return ifBreak$7([softline$8, ">"], ">");
}
/* MustacheStatement print helpers */
@@ -49896,13 +52606,13 @@ function printStartingTagEndMarker(node) {
function printOpeningMustache(node) {
const mustache = node.escaped === false ? "{{{" : "{{";
const strip = node.strip && node.strip.open ? "~" : "";
- return concat$C([mustache, strip]);
+ return [mustache, strip];
}
function printClosingMustache(node) {
const mustache = node.escaped === false ? "}}}" : "}}";
const strip = node.strip && node.strip.close ? "~" : "";
- return concat$C([strip, mustache]);
+ return [strip, mustache];
}
/* BlockStatement print helpers */
@@ -49910,92 +52620,117 @@ function printClosingMustache(node) {
function printOpeningBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.openStrip.open ? "~" : "";
- return concat$C([opening, strip, "#"]);
+ return [opening, strip, "#"];
}
function printOpeningBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.openStrip.close ? "~" : "";
- return concat$C([strip, closing]);
+ return [strip, closing];
}
function printClosingBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.closeStrip.open ? "~" : "";
- return concat$C([opening, strip, "/"]);
+ return [opening, strip, "/"];
}
function printClosingBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.closeStrip.close ? "~" : "";
- return concat$C([strip, closing]);
+ return [strip, closing];
}
function printInverseBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.inverseStrip.open ? "~" : "";
- return concat$C([opening, strip]);
+ return [opening, strip];
}
function printInverseBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.inverseStrip.close ? "~" : "";
- return concat$C([strip, closing]);
+ return [strip, closing];
}
function printOpenBlock(path, print) {
const node = path.getValue();
- return group$r(concat$C([printOpeningBlockOpeningMustache(node), printPathAndParams(path, print), printBlockParams(node.program), softline$j, printOpeningBlockClosingMustache(node)]));
+ const openingMustache = printOpeningBlockOpeningMustache(node);
+ const closingMustache = printOpeningBlockClosingMustache(node);
+ const attributes = [printPath(path, print)];
+ const params = printParams(path, print);
+
+ if (params) {
+ attributes.push(line$c, params);
+ }
+
+ if (isNonEmptyArray$4(node.program.blockParams)) {
+ const block = printBlockParams(node.program);
+ attributes.push(line$c, block);
+ }
+
+ return group$9([openingMustache, indent$5(attributes), softline$8, closingMustache]);
}
-function printElseBlock(node) {
- return concat$C([hardline$p, printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)]);
+function printElseBlock(node, options) {
+ return [options.htmlWhitespaceSensitivity === "ignore" ? hardline$b : "", printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)];
}
function printElseIfBlock(path, print) {
const parentNode = path.getParentNode(1);
- return concat$C([printInverseBlockOpeningMustache(parentNode), "else ", printPathAndParams(path, print), printInverseBlockClosingMustache(parentNode)]);
+ return [printInverseBlockOpeningMustache(parentNode), "else if ", printParams(path, print), printInverseBlockClosingMustache(parentNode)];
}
-function printCloseBlock(path, print) {
+function printCloseBlock(path, print, options) {
const node = path.getValue();
- return concat$C([blockStatementHasOnlyWhitespaceInProgram(node) ? softline$j : hardline$p, printClosingBlockOpeningMustache(node), path.call(print, "path"), printClosingBlockClosingMustache(node)]);
+
+ if (options.htmlWhitespaceSensitivity === "ignore") {
+ const escape = blockStatementHasOnlyWhitespaceInProgram(node) ? softline$8 : hardline$b;
+ return [escape, printClosingBlockOpeningMustache(node), print("path"), printClosingBlockClosingMustache(node)];
+ }
+
+ return [printClosingBlockOpeningMustache(node), print("path"), printClosingBlockClosingMustache(node)];
}
function blockStatementHasOnlyWhitespaceInProgram(node) {
- return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.program.body.every(n => isWhitespaceNode$1(n));
+ return isNodeOfSomeType(node, ["BlockStatement"]) && node.program.body.every(node => isWhitespaceNode(node));
}
function blockStatementHasElseIf(node) {
- return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType$1(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if";
+ return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if";
}
function blockStatementHasElse(node) {
- return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.inverse;
+ return isNodeOfSomeType(node, ["BlockStatement"]) && node.inverse;
}
-function printProgram(path, print) {
+function printProgram(path, print, options) {
const node = path.getValue();
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
return "";
}
- const program = path.call(print, "program");
- return indent$s(concat$C([hardline$p, program]));
+ const program = print("program");
+
+ if (options.htmlWhitespaceSensitivity === "ignore") {
+ return indent$5([hardline$b, program]);
+ }
+
+ return indent$5(program);
}
-function printInverse(path, print) {
+function printInverse(path, print, options) {
const node = path.getValue();
- const inverse = path.call(print, "inverse");
- const parts = concat$C([hardline$p, inverse]);
+ const inverse = print("inverse");
+ const printed = options.htmlWhitespaceSensitivity === "ignore" ? [hardline$b, inverse] : inverse;
if (blockStatementHasElseIf(node)) {
- return parts;
+ return printed;
}
if (blockStatementHasElse(node)) {
- return concat$C([printElseBlock(node), indent$s(parts)]);
+ return [printElseBlock(node, options), indent$5(printed)];
}
return "";
@@ -50003,8 +52738,22 @@ function printInverse(path, print) {
/* TextNode print helpers */
-function isInAttributeOfName(path, type) {
- return isParentOfSomeType$1(path, ["AttrNode"]) && path.getParentNode().name.toLowerCase() === type || isParentOfSomeType$1(path, ["ConcatStatement"]) && path.getParentNode(1).name.toLowerCase() === type;
+function getTextValueParts$3(value) {
+ return getDocParts$4(join$9(line$c, splitByHtmlWhitespace$1(value)));
+}
+
+function splitByHtmlWhitespace$1(string) {
+ return string.split(/[\t\n\f\r ]+/);
+}
+
+function getCurrentAttributeName(path) {
+ for (let depth = 0; depth < 2; depth++) {
+ const parentNode = path.getParentNode(depth);
+
+ if (parentNode && parentNode.type === "AttrNode") {
+ return parentNode.name.toLowerCase();
+ }
+ }
}
function countNewLines(string) {
@@ -50027,11 +52776,15 @@ function countTrailingNewLines(string) {
return countNewLines(newLines);
}
-function generateHardlines(number = 0, max = 0) {
- return new Array(Math.min(number, max)).fill(hardline$p);
+function generateHardlines(number = 0) {
+ return Array.from({
+ length: Math.min(number, NEWLINES_TO_PRESERVE_MAX)
+ }).fill(hardline$b);
}
/* StringLiteral print helpers */
+/** @typedef {import("../common/util").Quote} Quote */
+
/**
* Prints a string literal with the correct surrounding quotes based on
* `options.singleQuote` and the number of escaped quotes contained in
@@ -50039,34 +52792,32 @@ function generateHardlines(number = 0, max = 0) {
* in `common/util`, but has differences because of the way escaped characters
* are treated in hbs string literals.
* @param {string} stringLiteral - the string literal value
- * @param {object} options - the prettier options object
+ * @param {Quote} favoriteQuote - the user's preferred quote: `'` or `"`
*/
-function printStringLiteral(stringLiteral, options) {
- const double = {
- quote: '"',
- regex: /"/g
- };
- const single = {
- quote: "'",
- regex: /'/g
- };
- const preferred = options.singleQuote ? single : double;
- const alternate = preferred === single ? double : single;
- let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
- // enclosing the string, we might want to enclose with the alternate quote
- // instead, to minimize the number of escaped quotes.
+function printStringLiteral(stringLiteral, favoriteQuote) {
+ const {
+ quote,
+ regex
+ } = getPreferredQuote(stringLiteral, favoriteQuote);
+ return [quote, stringLiteral.replace(regex, `\\${quote}`), quote];
+}
+
+function needsOppositeQuote(path) {
+ let index = 0;
+ let parentNode = path.getParentNode(index);
+
+ while (parentNode && isNodeOfSomeType(parentNode, ["SubExpression"])) {
+ index++;
+ parentNode = path.getParentNode(index);
+ }
- if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
- const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
- const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
- shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
+ if (parentNode && isNodeOfSomeType(path.getParentNode(index + 1), ["ConcatStatement"]) && isNodeOfSomeType(path.getParentNode(index + 2), ["AttrNode"])) {
+ return true;
}
- const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
- const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
- return concat$C([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
+ return false;
}
/* SubExpression print helpers */
@@ -50079,7 +52830,7 @@ function printSubExpressionPathAndParams(path, print) {
return p;
}
- return indent$s(concat$C([p, line$l, group$r(params)]));
+ return indent$5([p, line$c, group$9(params)]);
}
/* misc. print helpers */
@@ -50092,115 +52843,106 @@ function printPathAndParams(path, print) {
return p;
}
- return indent$s(group$r(concat$C([p, line$l, params])));
+ return [indent$5([p, line$c, params]), softline$8];
}
function printPath(path, print) {
- return path.call(print, "path");
+ return print("path");
}
function printParams(path, print) {
const node = path.getValue();
const parts = [];
- if (node.params.length) {
+ if (node.params.length > 0) {
const params = path.map(print, "params");
parts.push(...params);
}
if (node.hash && node.hash.pairs.length > 0) {
- const hash = path.call(print, "hash");
+ const hash = print("hash");
parts.push(hash);
}
- if (!parts.length) {
+ if (parts.length === 0) {
return "";
}
- return join$i(line$l, parts);
+ return join$9(line$c, parts);
}
function printBlockParams(node) {
- if (!node || !node.blockParams.length) {
- return "";
- }
-
- return concat$C([" as |", node.blockParams.join(" "), "|"]);
+ return ["as |", node.blockParams.join(" "), "|"];
}
-function doesNotHaveHashParams(node) {
- return node.hash.pairs.length === 0;
-}
+var printerGlimmer = {
+ print,
+ massageAstNode: clean$6
+};
-function doesNotHavePositionalParams(node) {
- return node.params.length === 0;
-}
+var parsers$9 = {
+ get glimmer() {
+ return require("./parser-glimmer.js").parsers.glimmer;
+ }
-var printerGlimmer = {
- print: print$2,
- massageAstNode: clean_1$2
};
-var name$d = "Handlebars";
-var type$b = "markup";
+var name$5 = "Handlebars";
+var type$5 = "markup";
var color$5 = "#f7931e";
var aliases$3 = [
"hbs",
"htmlbars"
];
-var extensions$b = [
+var extensions$5 = [
".handlebars",
".hbs"
];
-var tmScope$b = "text.html.handlebars";
-var aceMode$b = "handlebars";
-var languageId$b = 155;
-var require$$0$4 = {
- name: name$d,
- type: type$b,
+var tmScope$5 = "text.html.handlebars";
+var aceMode$5 = "handlebars";
+var languageId$5 = 155;
+var require$$3 = {
+ name: name$5,
+ type: type$5,
color: color$5,
aliases: aliases$3,
- extensions: extensions$b,
- tmScope: tmScope$b,
- aceMode: aceMode$b,
- languageId: languageId$b
+ extensions: extensions$5,
+ tmScope: tmScope$5,
+ aceMode: aceMode$5,
+ languageId: languageId$5
};
-const languages$2 = [createLanguage(require$$0$4, () => ({
- since: null,
- // unreleased
+const createLanguage$4 = createLanguage$7;
+const printer$4 = printerGlimmer;
+const parsers$8 = parsers$9;
+const languages$5 = [createLanguage$4(require$$3, () => ({
+ since: "2.3.0",
parsers: ["glimmer"],
vscodeLanguageIds: ["handlebars"]
}))];
-const printers$2 = {
- glimmer: printerGlimmer
-};
-const parsers$2 = {
- get glimmer() {
- return require("./parser-glimmer").parsers.glimmer;
- }
-
+const printers$3 = {
+ glimmer: printer$4
};
var languageHandlebars = {
- languages: languages$2,
- printers: printers$2,
- parsers: parsers$2
+ languages: languages$5,
+ printers: printers$3,
+ parsers: parsers$8
};
function hasPragma$2(text) {
- return /^\s*#[^\S\n]*@(format|prettier)\s*(\n|$)/.test(text);
+ return /^\s*#[^\S\n]*@(?:format|prettier)\s*(?:\n|$)/.test(text);
}
-function insertPragma$4(text) {
+function insertPragma$6(text) {
return "# @format\n\n" + text;
}
-var pragma$2 = {
+var pragma$3 = {
hasPragma: hasPragma$2,
- insertPragma: insertPragma$4
+ insertPragma: insertPragma$6
};
-function locStart$d(node) {
+function locStart$a(node) {
if (typeof node.start === "number") {
return node.start;
}
@@ -50208,7 +52950,7 @@ function locStart$d(node) {
return node.loc && node.loc.start;
}
-function locEnd$j(node) {
+function locEnd$9(node) {
if (typeof node.end === "number") {
return node.end;
}
@@ -50217,108 +52959,108 @@ function locEnd$j(node) {
}
var loc$3 = {
- locStart: locStart$d,
- locEnd: locEnd$j
+ locStart: locStart$a,
+ locEnd: locEnd$9
};
const {
builders: {
- concat: concat$D,
- join: join$j,
- hardline: hardline$q,
- line: line$m,
- softline: softline$k,
- group: group$s,
- indent: indent$t,
- ifBreak: ifBreak$g
+ join: join$8,
+ hardline: hardline$a,
+ line: line$b,
+ softline: softline$7,
+ group: group$8,
+ indent: indent$4,
+ ifBreak: ifBreak$6
}
-} = document;
+} = require$$7$3;
const {
- isNextLineEmpty: isNextLineEmpty$b
-} = util;
+ isNextLineEmpty: isNextLineEmpty$2,
+ isNonEmptyArray: isNonEmptyArray$3
+} = util$8;
const {
insertPragma: insertPragma$5
-} = pragma$2;
+} = pragma$3;
const {
- locStart: locStart$e,
- locEnd: locEnd$k
+ locStart: locStart$9,
+ locEnd: locEnd$8
} = loc$3;
function genericPrint$3(path, options, print) {
- const n = path.getValue();
+ const node = path.getValue();
- if (!n) {
+ if (!node) {
return "";
}
- if (typeof n === "string") {
- return n;
+ if (typeof node === "string") {
+ return node;
}
- switch (n.kind) {
+ switch (node.kind) {
case "Document":
{
const parts = [];
- path.each((pathChild, index) => {
- parts.push(concat$D([pathChild.call(print)]));
+ path.each((pathChild, index, definitions) => {
+ parts.push(print());
- if (index !== n.definitions.length - 1) {
- parts.push(hardline$q);
+ if (index !== definitions.length - 1) {
+ parts.push(hardline$a);
- if (isNextLineEmpty$b(options.originalText, pathChild.getValue(), locEnd$k)) {
- parts.push(hardline$q);
+ if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), locEnd$8)) {
+ parts.push(hardline$a);
}
}
}, "definitions");
- return concat$D([concat$D(parts), hardline$q]);
+ return [...parts, hardline$a];
}
case "OperationDefinition":
{
- const hasOperation = options.originalText[locStart$e(n)] !== "{";
- const hasName = !!n.name;
- return concat$D([hasOperation ? n.operation : "", hasOperation && hasName ? concat$D([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "variableDefinitions"))])), softline$k, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
+ const hasOperation = options.originalText[locStart$9(node)] !== "{";
+ const hasName = Boolean(node.name);
+ return [hasOperation ? node.operation : "", hasOperation && hasName ? [" ", print("name")] : "", hasOperation && !hasName && isNonEmptyArray$3(node.variableDefinitions) ? " " : "", isNonEmptyArray$3(node.variableDefinitions) ? group$8(["(", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.map(print, "variableDefinitions"))]), softline$7, ")"]) : "", printDirectives(path, print, node), node.selectionSet ? !hasOperation && !hasName ? "" : " " : "", print("selectionSet")];
}
case "FragmentDefinition":
{
- return concat$D(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "variableDefinitions"))])), softline$k, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
+ return ["fragment ", print("name"), isNonEmptyArray$3(node.variableDefinitions) ? group$8(["(", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.map(print, "variableDefinitions"))]), softline$7, ")"]) : "", " on ", print("typeCondition"), printDirectives(path, print, node), " ", print("selectionSet")];
}
case "SelectionSet":
{
- return concat$D(["{", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$q, "}"]);
+ return ["{", indent$4([hardline$a, join$8(hardline$a, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))]), hardline$a, "}"];
}
case "Field":
{
- return group$s(concat$D([n.alias ? concat$D([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
+ return group$8([node.alias ? [print("alias"), ": "] : "", print("name"), node.arguments.length > 0 ? group$8(["(", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$7, ")"]) : "", printDirectives(path, print, node), node.selectionSet ? " " : "", print("selectionSet")]);
}
case "Name":
{
- return n.value;
+ return node.value;
}
case "StringValue":
{
- if (n.block) {
- return concat$D(['"""', hardline$q, join$j(hardline$q, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$q, '"""']);
+ if (node.block) {
+ return ['"""', hardline$a, join$8(hardline$a, node.value.replace(/"""/g, "\\$&").split("\n")), hardline$a, '"""'];
}
- return concat$D(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
+ return ['"', node.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"'];
}
case "IntValue":
case "FloatValue":
case "EnumValue":
{
- return n.value;
+ return node.value;
}
case "BooleanValue":
{
- return n.value ? "true" : "false";
+ return node.value ? "true" : "false";
}
case "NullValue":
@@ -50328,164 +53070,164 @@ function genericPrint$3(path, options, print) {
case "Variable":
{
- return concat$D(["$", path.call(print, "name")]);
+ return ["$", print("name")];
}
case "ListValue":
{
- return group$s(concat$D(["[", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "values"))])), softline$k, "]"]));
+ return group$8(["[", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.map(print, "values"))]), softline$7, "]"]);
}
case "ObjectValue":
{
- return group$s(concat$D(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "fields"))])), softline$k, ifBreak$g("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
+ return group$8(["{", options.bracketSpacing && node.fields.length > 0 ? " " : "", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.map(print, "fields"))]), softline$7, ifBreak$6("", options.bracketSpacing && node.fields.length > 0 ? " " : ""), "}"]);
}
case "ObjectField":
case "Argument":
{
- return concat$D([path.call(print, "name"), ": ", path.call(print, "value")]);
+ return [print("name"), ": ", print("value")];
}
case "Directive":
{
- return concat$D(["@", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : ""]);
+ return ["@", print("name"), node.arguments.length > 0 ? group$8(["(", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$7, ")"]) : ""];
}
case "NamedType":
{
- return path.call(print, "name");
+ return print("name");
}
case "VariableDefinition":
{
- return concat$D([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$D([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
+ return [print("variable"), ": ", print("type"), node.defaultValue ? [" = ", print("defaultValue")] : "", printDirectives(path, print, node)];
}
case "ObjectTypeExtension":
case "ObjectTypeDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$D([" implements ", concat$D(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$q, "}"]) : ""]);
+ return [print("description"), node.description ? hardline$a : "", node.kind === "ObjectTypeExtension" ? "extend " : "", "type ", print("name"), node.interfaces.length > 0 ? [" implements ", ...printInterfaces(path, options, print)] : "", printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$4([hardline$a, join$8(hardline$a, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$a, "}"] : ""];
}
case "FieldDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
+ return [print("description"), node.description ? hardline$a : "", print("name"), node.arguments.length > 0 ? group$8(["(", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$7, ")"]) : "", ": ", print("type"), printDirectives(path, print, node)];
}
case "DirectiveDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : "", n.repeatable ? " repeatable" : "", concat$D([" on ", join$j(" | ", path.map(print, "locations"))])]);
+ return [print("description"), node.description ? hardline$a : "", "directive ", "@", print("name"), node.arguments.length > 0 ? group$8(["(", indent$4([softline$7, join$8([ifBreak$6("", ", "), softline$7], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$7, ")"]) : "", node.repeatable ? " repeatable" : "", " on ", join$8(" | ", path.map(print, "locations"))];
}
case "EnumTypeExtension":
case "EnumTypeDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$q, "}"]) : ""]);
+ return [print("description"), node.description ? hardline$a : "", node.kind === "EnumTypeExtension" ? "extend " : "", "enum ", print("name"), printDirectives(path, print, node), node.values.length > 0 ? [" {", indent$4([hardline$a, join$8(hardline$a, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))]), hardline$a, "}"] : ""];
}
case "EnumValueDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", path.call(print, "name"), printDirectives(path, print, n)]);
+ return [print("description"), node.description ? hardline$a : "", print("name"), printDirectives(path, print, node)];
}
case "InputValueDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? n.description.block ? hardline$q : line$m : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$D([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
+ return [print("description"), node.description ? node.description.block ? hardline$a : line$b : "", print("name"), ": ", print("type"), node.defaultValue ? [" = ", print("defaultValue")] : "", printDirectives(path, print, node)];
}
case "InputObjectTypeExtension":
case "InputObjectTypeDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$q, "}"]) : ""]);
+ return [print("description"), node.description ? hardline$a : "", node.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", print("name"), printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$4([hardline$a, join$8(hardline$a, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$a, "}"] : ""];
}
case "SchemaDefinition":
{
- return concat$D(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$q, "}"]);
+ return ["schema", printDirectives(path, print, node), " {", node.operationTypes.length > 0 ? indent$4([hardline$a, join$8(hardline$a, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))]) : "", hardline$a, "}"];
}
case "OperationTypeDefinition":
{
- return concat$D([path.call(print, "operation"), ": ", path.call(print, "type")]);
+ return [print("operation"), ": ", print("type")];
}
case "InterfaceTypeExtension":
case "InterfaceTypeDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), n.interfaces.length > 0 ? concat$D([" implements ", concat$D(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$q, "}"]) : ""]);
+ return [print("description"), node.description ? hardline$a : "", node.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", print("name"), node.interfaces.length > 0 ? [" implements ", ...printInterfaces(path, options, print)] : "", printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$4([hardline$a, join$8(hardline$a, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$a, "}"] : ""];
}
case "FragmentSpread":
{
- return concat$D(["...", path.call(print, "name"), printDirectives(path, print, n)]);
+ return ["...", print("name"), printDirectives(path, print, node)];
}
case "InlineFragment":
{
- return concat$D(["...", n.typeCondition ? concat$D([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
+ return ["...", node.typeCondition ? [" on ", print("typeCondition")] : "", printDirectives(path, print, node), " ", print("selectionSet")];
}
case "UnionTypeExtension":
case "UnionTypeDefinition":
{
- return group$s(concat$D([path.call(print, "description"), n.description ? hardline$q : "", group$s(concat$D([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$D([" =", ifBreak$g("", " "), indent$t(concat$D([ifBreak$g(concat$D([line$m, " "])), join$j(concat$D([line$m, "| "]), path.map(print, "types"))]))]) : ""]))]));
+ return group$8([print("description"), node.description ? hardline$a : "", group$8([node.kind === "UnionTypeExtension" ? "extend " : "", "union ", print("name"), printDirectives(path, print, node), node.types.length > 0 ? [" =", ifBreak$6("", " "), indent$4([ifBreak$6([line$b, " "]), join$8([line$b, "| "], path.map(print, "types"))])] : ""])]);
}
case "ScalarTypeExtension":
case "ScalarTypeDefinition":
{
- return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
+ return [print("description"), node.description ? hardline$a : "", node.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", print("name"), printDirectives(path, print, node)];
}
case "NonNullType":
{
- return concat$D([path.call(print, "type"), "!"]);
+ return [print("type"), "!"];
}
case "ListType":
{
- return concat$D(["[", path.call(print, "type"), "]"]);
+ return ["[", print("type"), "]"];
}
default:
/* istanbul ignore next */
- throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
+ throw new Error("unknown graphql type: " + JSON.stringify(node.kind));
}
}
-function printDirectives(path, print, n) {
- if (n.directives.length === 0) {
+function printDirectives(path, print, node) {
+ if (node.directives.length === 0) {
return "";
}
- const printed = join$j(line$m, path.map(print, "directives"));
+ const printed = join$8(line$b, path.map(print, "directives"));
- if (n.kind === "FragmentDefinition" || n.kind === "OperationDefinition") {
- return group$s(concat$D([line$m, printed]));
+ if (node.kind === "FragmentDefinition" || node.kind === "OperationDefinition") {
+ return group$8([line$b, printed]);
}
- return concat$D([" ", group$s(indent$t(concat$D([softline$k, printed])))]);
+ return [" ", group$8(indent$4([softline$7, printed]))];
}
function printSequence(sequencePath, options, print) {
const count = sequencePath.getValue().length;
return sequencePath.map((path, i) => {
- const printed = print(path);
+ const printed = print();
- if (isNextLineEmpty$b(options.originalText, path.getValue(), locEnd$k) && i < count - 1) {
- return concat$D([printed, hardline$q]);
+ if (isNextLineEmpty$2(options.originalText, path.getValue(), locEnd$8) && i < count - 1) {
+ return [printed, hardline$a];
}
return printed;
});
}
-function canAttachComment$1(node) {
+function canAttachComment(node) {
return node.kind && node.kind !== "Comment";
}
-function printComment$3(commentPath) {
+function printComment(commentPath) {
const comment = commentPath.getValue();
if (comment.kind === "Comment") {
@@ -50514,145 +53256,156 @@ function printInterfaces(path, options, print) {
const textBetween = options.originalText.slice(interfaceNode.loc.end, nextInterfaceNode.loc.start);
const hasComment = textBetween.includes("#");
const separator = textBetween.replace(/#.*/g, "").trim();
- parts.push(separator === "," ? "," : " &");
- parts.push(hasComment ? line$m : " ");
+ parts.push(separator === "," ? "," : " &", hasComment ? line$b : " ");
}
}
return parts;
}
-function clean$4()
-/*node, newNode , parent*/
-{}
+function
+ /*node, newNode , parent*/
+clean$5() {}
-clean$4.ignoredProperties = new Set(["loc", "comments"]);
+clean$5.ignoredProperties = new Set(["loc", "comments"]);
-function hasPrettierIgnore$4(path) {
+function hasPrettierIgnore$6(path) {
const node = path.getValue();
return node && Array.isArray(node.comments) && node.comments.some(comment => comment.value.trim() === "prettier-ignore");
}
var printerGraphql = {
print: genericPrint$3,
- massageAstNode: clean$4,
- hasPrettierIgnore: hasPrettierIgnore$4,
+ massageAstNode: clean$5,
+ hasPrettierIgnore: hasPrettierIgnore$6,
insertPragma: insertPragma$5,
- printComment: printComment$3,
- canAttachComment: canAttachComment$1
+ printComment,
+ canAttachComment
};
-var options$4 = {
- bracketSpacing: commonOptions.bracketSpacing
+const commonOptions$3 = commonOptions$6; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
+
+var options$7 = {
+ bracketSpacing: commonOptions$3.bracketSpacing
};
-var name$e = "GraphQL";
-var type$c = "data";
-var color$6 = "#e10098";
-var extensions$c = [
+var parsers$7 = {
+ get graphql() {
+ return require("./parser-graphql.js").parsers.graphql;
+ }
+
+};
+
+var name$4 = "GraphQL";
+var type$4 = "data";
+var color$4 = "#e10098";
+var extensions$4 = [
".graphql",
".gql",
".graphqls"
];
-var tmScope$c = "source.graphql";
-var aceMode$c = "text";
-var languageId$c = 139;
-var require$$0$5 = {
- name: name$e,
- type: type$c,
- color: color$6,
- extensions: extensions$c,
- tmScope: tmScope$c,
- aceMode: aceMode$c,
- languageId: languageId$c
+var tmScope$4 = "source.graphql";
+var aceMode$4 = "text";
+var languageId$4 = 139;
+var require$$4$4 = {
+ name: name$4,
+ type: type$4,
+ color: color$4,
+ extensions: extensions$4,
+ tmScope: tmScope$4,
+ aceMode: aceMode$4,
+ languageId: languageId$4
};
-const languages$3 = [createLanguage(require$$0$5, () => ({
+const createLanguage$3 = createLanguage$7;
+const printer$3 = printerGraphql;
+const options$6 = options$7;
+const parsers$6 = parsers$7;
+const languages$4 = [createLanguage$3(require$$4$4, () => ({
since: "1.5.0",
parsers: ["graphql"],
vscodeLanguageIds: ["graphql"]
}))];
-const printers$3 = {
- graphql: printerGraphql
-};
-const parsers$3 = {
- get graphql() {
- return require("./parser-graphql").parsers.graphql;
- }
-
+const printers$2 = {
+ graphql: printer$3
};
var languageGraphql = {
- languages: languages$3,
- options: options$4,
- printers: printers$3,
- parsers: parsers$3
+ languages: languages$4,
+ options: options$6,
+ printers: printers$2,
+ parsers: parsers$6
};
-function locStart$f(node) {
+function locStart$8(node) {
return node.position.start.offset;
}
-function locEnd$l(node) {
+function locEnd$7(node) {
return node.position.end.offset;
}
-var loc$4 = {
- locStart: locStart$f,
- locEnd: locEnd$l
+var loc$2 = {
+ locStart: locStart$8,
+ locEnd: locEnd$7
};
-var json = {
- "cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?",
+var require$$2 = {
+ "cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?",
"kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]",
"punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"
};
const {
- getLast: getLast$b
-} = util;
+ getLast: getLast$5
+} = util$8;
const {
- locStart: locStart$g,
- locEnd: locEnd$m
-} = loc$4;
+ locStart: locStart$7,
+ locEnd: locEnd$6
+} = loc$2;
const {
cjkPattern,
kPattern,
- punctuationPattern
-} = json;
-const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "wikiLink", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
-const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
+ punctuationPattern: punctuationPattern$1
+} = require$$2;
+const INLINE_NODE_TYPES$1 = ["liquidNode", "inlineCode", "emphasis", "esComment", "strong", "delete", "wikiLink", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
+const INLINE_NODE_WRAPPER_TYPES$1 = [...INLINE_NODE_TYPES$1, "tableCell", "paragraph", "heading"];
const kRegex = new RegExp(kPattern);
-const punctuationRegex = new RegExp(punctuationPattern);
+const punctuationRegex = new RegExp(punctuationPattern$1);
/**
* split text into whitespaces and words
* @param {string} text
- * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
*/
-function splitText(text, options) {
+function splitText$2(text, options) {
const KIND_NON_CJK = "non-cjk";
const KIND_CJ_LETTER = "cj-letter";
const KIND_K_LETTER = "k-letter";
const KIND_CJK_PUNCTUATION = "cjk-punctuation";
+ /** @type {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} */
+
const nodes = [];
- (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/).forEach((token, index, tokens) => {
+ const tokens = (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/);
+
+ for (const [index, token] of tokens.entries()) {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
- return;
+ continue;
} // word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
- return;
+ continue;
}
- token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => {
+ const innerTokens = token.split(new RegExp(`(${cjkPattern})`));
+
+ for (const [innerIndex, innerToken] of innerTokens.entries()) {
if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
- return;
+ continue;
} // non-CJK word
@@ -50663,11 +53416,11 @@ function splitText(text, options) {
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
- hasTrailingPunctuation: punctuationRegex.test(getLast$b(innerToken))
+ hasTrailingPunctuation: punctuationRegex.test(getLast$5(innerToken))
});
}
- return;
+ continue;
} // CJK character
@@ -50684,12 +53437,13 @@ function splitText(text, options) {
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
});
- });
- });
+ }
+ }
+
return nodes;
function appendNode(node) {
- const lastNode = getLast$b(nodes);
+ const lastNode = getLast$5(nodes);
if (lastNode && lastNode.type === "word") {
if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
@@ -50714,7 +53468,7 @@ function splitText(text, options) {
}
}
-function getOrderedListItemInfo(orderListItem, originalText) {
+function getOrderedListItemInfo$1(orderListItem, originalText) {
const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
return {
numberText,
@@ -50723,7 +53477,7 @@ function getOrderedListItemInfo(orderListItem, originalText) {
};
}
-function hasGitDiffFriendlyOrderedList(node, options) {
+function hasGitDiffFriendlyOrderedList$1(node, options) {
if (!node.ordered) {
return false;
}
@@ -50732,11 +53486,11 @@ function hasGitDiffFriendlyOrderedList(node, options) {
return false;
}
- const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
- const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
+ const firstNumber = Number(getOrderedListItemInfo$1(node.children[0], options.originalText).numberText);
+ const secondNumber = Number(getOrderedListItemInfo$1(node.children[1], options.originalText).numberText);
if (firstNumber === 0 && node.children.length > 2) {
- const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
+ const thirdNumber = Number(getOrderedListItemInfo$1(node.children[2], options.originalText).numberText);
return secondNumber === 1 && thirdNumber === 1;
}
@@ -50745,7 +53499,7 @@ function hasGitDiffFriendlyOrderedList(node, options) {
// https://github.com/remarkjs/remark/issues/512
-function getFencedCodeBlockValue(node, originalText) {
+function getFencedCodeBlockValue$2(node, originalText) {
const {
value
} = node;
@@ -50758,64 +53512,58 @@ function getFencedCodeBlockValue(node, originalText) {
return value;
}
-function mapAst(ast, handler) {
+function mapAst$1(ast, handler) {
return function preorder(node, index, parentStack) {
- parentStack = parentStack || [];
const newNode = Object.assign({}, handler(node, index, parentStack));
if (newNode.children) {
- newNode.children = newNode.children.map((child, index) => {
- return preorder(child, index, [newNode].concat(parentStack));
- });
+ newNode.children = newNode.children.map((child, index) => preorder(child, index, [newNode, ...parentStack]));
}
return newNode;
- }(ast, null, null);
+ }(ast, null, []);
}
-function isAutolink(node) {
+function isAutolink$1(node) {
if (!node || node.type !== "link" || node.children.length !== 1) {
return false;
}
const child = node.children[0];
- return child && locStart$g(node) === locStart$g(child) && locEnd$m(node) === locEnd$m(child);
+ return child && locStart$7(node) === locStart$7(child) && locEnd$6(node) === locEnd$6(child);
}
-var utils$9 = {
- mapAst,
- splitText,
- punctuationPattern,
- getFencedCodeBlockValue,
- getOrderedListItemInfo,
- hasGitDiffFriendlyOrderedList,
- INLINE_NODE_TYPES,
- INLINE_NODE_WRAPPER_TYPES,
- isAutolink
+var utils$2 = {
+ mapAst: mapAst$1,
+ splitText: splitText$2,
+ punctuationPattern: punctuationPattern$1,
+ getFencedCodeBlockValue: getFencedCodeBlockValue$2,
+ getOrderedListItemInfo: getOrderedListItemInfo$1,
+ hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
+ INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
+ INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1,
+ isAutolink: isAutolink$1
};
const {
inferParserByLanguage: inferParserByLanguage$1,
- getMaxContinuousCount: getMaxContinuousCount$2
-} = util;
+ getMaxContinuousCount: getMaxContinuousCount$1
+} = util$8;
const {
builders: {
- hardline: hardline$r,
- concat: concat$E,
+ hardline: hardline$9,
markAsRoot: markAsRoot$2
},
utils: {
- replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$2
+ replaceEndOfLine
}
-} = document;
-const {
- print: printFrontMatter$1
-} = frontMatter;
+} = require$$7$3;
+const printFrontMatter$1 = print_1;
const {
getFencedCodeBlockValue: getFencedCodeBlockValue$1
-} = utils$9;
+} = utils$2;
-function embed$2(path, print, textToDoc, options) {
+function embed$6(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === "code" && node.lang !== null) {
@@ -50823,13 +53571,19 @@ function embed$2(path, print, textToDoc, options) {
if (parser) {
const styleUnit = options.__inJsTemplate ? "~" : "`";
- const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$2(node.value, styleUnit) + 1));
- const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
+ const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$1(node.value, styleUnit) + 1));
+ const newOptions = {
parser
- }, {
+ };
+
+ if (node.lang === "tsx") {
+ newOptions.filepath = "dummy.tsx";
+ }
+
+ const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), newOptions, {
stripTrailingHardline: true
});
- return markAsRoot$2(concat$E([style, node.lang, node.meta ? " " + node.meta : "", hardline$r, replaceNewlinesWithLiterallines$2(doc), hardline$r, style]));
+ return markAsRoot$2([style, node.lang, node.meta ? " " + node.meta : "", hardline$9, replaceEndOfLine(doc), hardline$9, style]);
}
}
@@ -50839,11 +53593,11 @@ function embed$2(path, print, textToDoc, options) {
// MDX
case "importExport":
- return concat$E([textToDoc(node.value, {
+ return [textToDoc(node.value, {
parser: "babel"
}, {
stripTrailingHardline: true
- }), hardline$r]);
+ }), hardline$9];
case "jsx":
return textToDoc(`<$>${node.value}$>`, {
@@ -50857,40 +53611,38 @@ function embed$2(path, print, textToDoc, options) {
return null;
}
-var embed_1$2 = embed$2;
+var embed_1$2 = embed$6;
-const {
- parse: parseFrontMatter$1
-} = frontMatter;
+const parseFrontMatter = parse_1;
const pragmas = ["format", "prettier"];
-function startWithPragma(text) {
+function startWithPragma$1(text) {
const pragma = `@(${pragmas.join("|")})`;
- const regex = new RegExp([``, ``].join("|"), "m");
+ const regex = new RegExp([``, `{\\s*\\/\\*\\s*${pragma}\\s*\\*\\/\\s*}`, ``].join("|"), "m");
const matched = text.match(regex);
return matched && matched.index === 0;
}
-var pragma$3 = {
- startWithPragma,
- hasPragma: text => startWithPragma(parseFrontMatter$1(text).content.trimStart()),
+var pragma$2 = {
+ startWithPragma: startWithPragma$1,
+ hasPragma: text => startWithPragma$1(parseFrontMatter(text).content.trimStart()),
insertPragma: text => {
- const extracted = parseFrontMatter$1(text);
+ const extracted = parseFrontMatter(text);
const pragma = ``;
return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
}
};
+const getLast$4 = getLast_1;
const {
- getOrderedListItemInfo: getOrderedListItemInfo$1,
- mapAst: mapAst$1,
+ getOrderedListItemInfo,
+ mapAst,
splitText: splitText$1
-} = utils$9; // 0x0 ~ 0x10ffff
-// eslint-disable-next-line no-control-regex
+} = utils$2; // 0x0 ~ 0x10ffff
-const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
+const isSingleCharRegex = /^.$/su;
-function preprocess$1(ast, options) {
+function preprocess$5(ast, options) {
ast = restoreUnescapedCharacter(ast, options);
ast = mergeContinuousTexts(ast);
ast = transformInlineCode(ast);
@@ -50903,32 +53655,32 @@ function preprocess$1(ast, options) {
}
function transformImportExport(ast) {
- return mapAst$1(ast, node => {
+ return mapAst(ast, node => {
if (node.type !== "import" && node.type !== "export") {
return node;
}
- return Object.assign({}, node, {
+ return Object.assign(Object.assign({}, node), {}, {
type: "importExport"
});
});
}
function transformInlineCode(ast) {
- return mapAst$1(ast, node => {
+ return mapAst(ast, node => {
if (node.type !== "inlineCode") {
return node;
}
- return Object.assign({}, node, {
+ return Object.assign(Object.assign({}, node), {}, {
value: node.value.replace(/\s+/g, " ")
});
});
}
function restoreUnescapedCharacter(ast, options) {
- return mapAst$1(ast, node => node.type !== "text" || node.value === "*" || node.value === "_" || // handle these cases in printer
- !isSingleCharRegex.test(node.value) || node.position.end.offset - node.position.start.offset === node.value.length ? node : Object.assign({}, node, {
+ return mapAst(ast, node => node.type !== "text" || node.value === "*" || node.value === "_" || // handle these cases in printer
+ !isSingleCharRegex.test(node.value) || node.position.end.offset - node.position.start.offset === node.value.length ? node : Object.assign(Object.assign({}, node), {}, {
value: options.originalText.slice(node.position.start.offset, node.position.end.offset)
}));
}
@@ -50945,13 +53697,13 @@ function mergeContinuousImportExport(ast) {
}
function mergeChildren(ast, shouldMerge, mergeNode) {
- return mapAst$1(ast, node => {
+ return mapAst(ast, node => {
if (!node.children) {
return node;
}
const children = node.children.reduce((current, child) => {
- const lastChild = current[current.length - 1];
+ const lastChild = getLast$4(current);
if (lastChild && shouldMerge(lastChild, child)) {
current.splice(-1, 1, mergeNode(lastChild, child));
@@ -50961,7 +53713,7 @@ function mergeChildren(ast, shouldMerge, mergeNode) {
return current;
}, []);
- return Object.assign({}, node, {
+ return Object.assign(Object.assign({}, node), {}, {
children
});
});
@@ -50979,7 +53731,7 @@ function mergeContinuousTexts(ast) {
}
function splitTextIntoSentences(ast, options) {
- return mapAst$1(ast, (node, index, [parentNode]) => {
+ return mapAst(ast, (node, index, [parentNode]) => {
if (node.type !== "text") {
return node;
}
@@ -51007,10 +53759,10 @@ function splitTextIntoSentences(ast, options) {
}
function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
- return mapAst$1(ast, (node, index, parentStack) => {
+ return mapAst(ast, (node, index, parentStack) => {
if (node.type === "code") {
// the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
- const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
+ const isIndented = /^\n?(?: {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
node.isIndented = isIndented;
if (isIndented) {
@@ -51033,8 +53785,8 @@ function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
}
function markAlignedList(ast, options) {
- return mapAst$1(ast, (node, index, parentStack) => {
- if (node.type === "list" && node.children.length !== 0) {
+ return mapAst(ast, (node, index, parentStack) => {
+ if (node.type === "list" && node.children.length > 0) {
// if one of its parents is not aligned, it's not possible to be aligned in sub-lists
for (let i = 0; i < parentStack.length; i++) {
const parent = parentStack[i];
@@ -51065,7 +53817,7 @@ function markAlignedList(ast, options) {
}
const [firstItem, secondItem] = list.children;
- const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
+ const firstInfo = getOrderedListItemInfo(firstItem, options.originalText);
if (firstInfo.leadingSpaces.length > 1) {
/**
@@ -51135,23 +53887,23 @@ function markAlignedList(ast, options) {
*/
- const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
+ const secondInfo = getOrderedListItemInfo(secondItem, options.originalText);
return secondInfo.leadingSpaces.length > 1;
}
}
-var printPreprocess$1 = preprocess$1;
+var printPreprocess$2 = preprocess$5;
const {
- isFrontMatterNode: isFrontMatterNode$3
-} = util;
+ isFrontMatterNode: isFrontMatterNode$2
+} = util$8;
const {
- startWithPragma: startWithPragma$1
-} = pragma$3;
-const ignoredProperties$3 = new Set(["position", "raw" // front-matter
+ startWithPragma
+} = pragma$2;
+const ignoredProperties$1 = new Set(["position", "raw" // front-matter
]);
-function clean$5(ast, newObj, parent) {
+function clean$4(ast, newObj, parent) {
// for codeblock
if (ast.type === "front-matter" || ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
delete newObj.value;
@@ -51188,62 +53940,64 @@ function clean$5(ast, newObj, parent) {
} // for insert pragma
- if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$3(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && startWithPragma$1(ast.value)) {
+ if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$2(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && startWithPragma(ast.value)) {
return null;
}
}
-clean$5.ignoredProperties = ignoredProperties$3;
-var clean_1$3 = clean$5;
+clean$4.ignoredProperties = ignoredProperties$1;
+var clean_1$1 = clean$4;
const {
- getLast: getLast$c,
- getMinNotPresentContinuousCount: getMinNotPresentContinuousCount$1,
- getMaxContinuousCount: getMaxContinuousCount$3,
- getStringWidth: getStringWidth$4
-} = util;
+ getLast: getLast$3,
+ getMinNotPresentContinuousCount,
+ getMaxContinuousCount,
+ getStringWidth,
+ isNonEmptyArray: isNonEmptyArray$2
+} = util$8;
const {
builders: {
- breakParent: breakParent$6,
- concat: concat$F,
- join: join$k,
- line: line$n,
- literalline: literalline$4,
- markAsRoot: markAsRoot$3,
- hardline: hardline$s,
- softline: softline$l,
- ifBreak: ifBreak$h,
- fill: fill$5,
- align: align$5,
- indent: indent$u,
- group: group$t
+ breakParent: breakParent$4,
+ join: join$7,
+ line: line$a,
+ literalline: literalline$3,
+ markAsRoot: markAsRoot$1,
+ hardline: hardline$8,
+ softline: softline$6,
+ ifBreak: ifBreak$5,
+ fill: fill$4,
+ align: align$1,
+ indent: indent$3,
+ group: group$7,
+ hardlineWithoutBreakParent
},
utils: {
- normalizeDoc: normalizeDoc$1
+ normalizeDoc,
+ replaceTextEndOfLine: replaceTextEndOfLine$7
},
printer: {
- printDocToString: printDocToString$3
+ printDocToString
}
-} = document;
+} = require$$7$3;
+const embed$5 = embed_1$2;
const {
- replaceEndOfLineWith: replaceEndOfLineWith$1
-} = util;
-const {
- insertPragma: insertPragma$6
-} = pragma$3;
+ insertPragma: insertPragma$4
+} = pragma$2;
const {
- locStart: locStart$h,
- locEnd: locEnd$n
-} = loc$4;
+ locStart: locStart$6,
+ locEnd: locEnd$5
+} = loc$2;
+const preprocess$4 = printPreprocess$2;
+const clean$3 = clean_1$1;
const {
- getFencedCodeBlockValue: getFencedCodeBlockValue$2,
- hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
- splitText: splitText$2,
- punctuationPattern: punctuationPattern$1,
- INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
- INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1,
- isAutolink: isAutolink$1
-} = utils$9;
+ getFencedCodeBlockValue,
+ hasGitDiffFriendlyOrderedList,
+ splitText,
+ punctuationPattern,
+ INLINE_NODE_TYPES,
+ INLINE_NODE_WRAPPER_TYPES,
+ isAutolink
+} = utils$2;
/**
* @typedef {import("../document").Doc} Doc
*/
@@ -51252,11 +54006,11 @@ const TRAILING_HARDLINE_NODES = new Set(["importExport"]);
const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link", "wikiLink"];
const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]);
-function genericPrint$4(path, options, print) {
+function genericPrint$2(path, options, print) {
const node = path.getValue();
if (shouldRemainTheSameContent(path)) {
- return concat$F(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
+ return splitText(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options));
}
switch (node.type) {
@@ -51268,24 +54022,24 @@ function genericPrint$4(path, options, print) {
return "";
}
- return concat$F([normalizeDoc$1(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode(node).type) ? hardline$s : ""]);
+ return [normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode$2(node).type) ? hardline$8 : ""];
case "paragraph":
- return printChildren$1(path, options, print, {
- postprocessor: fill$5
+ return printChildren$4(path, options, print, {
+ postprocessor: fill$4
});
case "sentence":
- return printChildren$1(path, options, print);
+ return printChildren$4(path, options, print);
case "word":
{
let escapedValue = node.value.replace(/\*/g, "\\$&") // escape all `*`
- .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
+ .replace(new RegExp([`(^|${punctuationPattern})(_+)`, `(_+)(${punctuationPattern}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
const isFirstSentence = (node, name, index) => node.type === "sentence" && index === 0;
- const isLastChildAutolink = (node, name, index) => isAutolink$1(node.children[index - 1]);
+ const isLastChildAutolink = (node, name, index) => isAutolink(node.children[index - 1]);
if (escapedValue !== node.value && (path.match(undefined, isFirstSentence, isLastChildAutolink) || path.match(undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, isLastChildAutolink))) {
// backslash is parsed as part of autolinks, so we need to remove it
@@ -51301,7 +54055,7 @@ function genericPrint$4(path, options, print) {
const index = parentNode.children.indexOf(node);
const nextNode = parentNode.children[index + 1];
const proseWrap = // leading char that may cause different syntax
- nextNode && /^>|^([*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap;
+ nextNode && /^>|^(?:[*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap;
return printLine(path, node.value, {
proseWrap
});
@@ -51311,7 +54065,7 @@ function genericPrint$4(path, options, print) {
{
let style;
- if (isAutolink$1(node.children[0])) {
+ if (isAutolink(node.children[0])) {
style = options.originalText[node.position.start.offset];
} else {
const parentNode = path.getParentNode();
@@ -51319,25 +54073,25 @@ function genericPrint$4(path, options, print) {
const prevNode = parentNode.children[index - 1];
const nextNode = parentNode.children[index + 1];
const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
- prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$c(prevNode.children).type === "word" && !getLast$c(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
- style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
+ prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$3(prevNode.children).type === "word" && !getLast$3(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
+ style = hasPrevOrNextWord || getAncestorNode(path, "emphasis") ? "*" : "_";
}
- return concat$F([style, printChildren$1(path, options, print), style]);
+ return [style, printChildren$4(path, options, print), style];
}
case "strong":
- return concat$F(["**", printChildren$1(path, options, print), "**"]);
+ return ["**", printChildren$4(path, options, print), "**"];
case "delete":
- return concat$F(["~~", printChildren$1(path, options, print), "~~"]);
+ return ["~~", printChildren$4(path, options, print), "~~"];
case "inlineCode":
{
- const backtickCount = getMinNotPresentContinuousCount$1(node.value, "`");
+ const backtickCount = getMinNotPresentContinuousCount(node.value, "`");
const style = "`".repeat(backtickCount || 1);
const gap = backtickCount && !/^\s/.test(node.value) ? " " : "";
- return concat$F([style, gap, node.value, gap, style]);
+ return [style, gap, node.value, gap, style];
}
case "wikiLink":
@@ -51350,7 +54104,7 @@ function genericPrint$4(path, options, print) {
contents = node.value.replace(/[\t\n]+/g, " ");
}
- return concat$F(["[[", contents, "]]"]);
+ return ["[[", contents, "]]"];
}
case "link":
@@ -51360,61 +54114,62 @@ function genericPrint$4(path, options, print) {
const mailto = "mailto:";
const url = // is parsed as { url: "mailto:hello@example.com" }
node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
- return concat$F(["<", url, ">"]);
+ return ["<", url, ">"];
}
case "[":
- return concat$F(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
+ return ["[", printChildren$4(path, 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$F(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
+ return ["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"];
case "blockquote":
- return concat$F(["> ", align$5("> ", printChildren$1(path, options, print))]);
+ return ["> ", align$1("> ", printChildren$4(path, options, print))];
case "heading":
- return concat$F(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
+ return ["#".repeat(node.depth) + " ", printChildren$4(path, options, print)];
case "code":
{
if (node.isIndented) {
// indented code block
const alignment = " ".repeat(4);
- return align$5(alignment, concat$F([alignment, concat$F(replaceEndOfLineWith$1(node.value, hardline$s))]));
+ return align$1(alignment, [alignment, ...replaceTextEndOfLine$7(node.value, hardline$8)]);
} // fenced code block
const styleUnit = options.__inJsTemplate ? "~" : "`";
- const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$3(node.value, styleUnit) + 1));
- return concat$F([style, node.lang || "", node.meta ? " " + node.meta : "", hardline$s, concat$F(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$s)), hardline$s, style]);
+ const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1));
+ return [style, node.lang || "", node.meta ? " " + node.meta : "", hardline$8, ...replaceTextEndOfLine$7(getFencedCodeBlockValue(node, options.originalText), hardline$8), hardline$8, style];
}
case "html":
{
const parentNode = path.getParentNode();
- const value = parentNode.type === "root" && getLast$c(parentNode.children) === node ? node.value.trimEnd() : node.value;
- const isHtmlComment = /^$/.test(value);
- return concat$F(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$s : markAsRoot$3(literalline$4)));
+ const value = parentNode.type === "root" && getLast$3(parentNode.children) === node ? node.value.trimEnd() : node.value;
+ const isHtmlComment = /^$/s.test(value);
+ return replaceTextEndOfLine$7(value, // @ts-expect-error
+ isHtmlComment ? hardline$8 : markAsRoot$1(literalline$3));
}
case "list":
{
const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
- const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
- return printChildren$1(path, options, print, {
+ const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList(node, options);
+ return printChildren$4(path, options, print, {
processor: (childPath, index) => {
const prefix = getPrefix();
const childNode = childPath.getValue();
if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
- return concat$F([prefix, printListItem(childPath, options, print, prefix)]);
+ return [prefix, printListItem(childPath, options, print, prefix)];
}
- return concat$F([prefix, align$5(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
+ return [prefix, align$1(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))];
function getPrefix() {
const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
@@ -51428,7 +54183,7 @@ function genericPrint$4(path, options, print) {
case "thematicBreak":
{
- const counter = getAncestorCounter$1(path, "list");
+ const counter = getAncestorCounter(path, "list");
if (counter === -1) {
return "---";
@@ -51439,21 +54194,21 @@ function genericPrint$4(path, options, print) {
}
case "linkReference":
- return concat$F(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$F(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
+ return ["[", printChildren$4(path, options, print), "]", node.referenceType === "full" ? ["[", node.identifier, "]"] : node.referenceType === "collapsed" ? "[]" : ""];
case "imageReference":
switch (node.referenceType) {
case "full":
- return concat$F(["![", node.alt || "", "][", node.identifier, "]"]);
+ return ["![", node.alt || "", "][", node.identifier, "]"];
default:
- return concat$F(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
+ return ["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""];
}
case "definition":
{
- const lineOrSpace = options.proseWrap === "always" ? line$n : " ";
- return group$t(concat$F([concat$F(["[", node.identifier, "]:"]), indent$u(concat$F([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$F([lineOrSpace, printTitle(node.title, options, false)])]))]));
+ const lineOrSpace = options.proseWrap === "always" ? line$a : " ";
+ return group$7(["[", node.identifier, "]:", indent$3([lineOrSpace, printUrl(node.url), node.title === null ? "" : [lineOrSpace, printTitle(node.title, options, false)]])]);
}
// `footnote` requires `.use(footnotes, {inlineNotes: true})`, we are not using this option
// https://github.com/remarkjs/remark-footnotes#optionsinlinenotes
@@ -51461,51 +54216,52 @@ function genericPrint$4(path, options, print) {
/* istanbul ignore next */
case "footnote":
- return concat$F(["[^", printChildren$1(path, options, print), "]"]);
+ return ["[^", printChildren$4(path, options, print), "]"];
case "footnoteReference":
- return concat$F(["[^", node.identifier, "]"]);
+ return ["[^", node.identifier, "]"];
case "footnoteDefinition":
{
const nextNode = path.getParentNode().children[path.getName() + 1];
const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
- return concat$F(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$t(concat$F([align$5(" ".repeat(4), printChildren$1(path, options, print, {
- processor: (childPath, index) => {
- return index === 0 ? group$t(concat$F([softline$l, childPath.call(print)])) : childPath.call(print);
- }
- })), nextNode && nextNode.type === "footnoteDefinition" ? softline$l : ""]))]);
+ return ["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$4(path, options, print) : group$7([align$1(" ".repeat(4), printChildren$4(path, options, print, {
+ processor: (childPath, index) => index === 0 ? group$7([softline$6, print()]) : print()
+ })), nextNode && nextNode.type === "footnoteDefinition" ? softline$6 : ""])];
}
case "table":
return printTable(path, options, print);
case "tableCell":
- return printChildren$1(path, options, print);
+ return printChildren$4(path, options, print);
case "break":
- return /\s/.test(options.originalText[node.position.start.offset]) ? concat$F([" ", markAsRoot$3(literalline$4)]) : concat$F(["\\", hardline$s]);
+ return /\s/.test(options.originalText[node.position.start.offset]) ? [" ", markAsRoot$1(literalline$3)] : ["\\", hardline$8];
case "liquidNode":
- return concat$F(replaceEndOfLineWith$1(node.value, hardline$s));
+ return replaceTextEndOfLine$7(node.value, hardline$8);
// MDX
// fallback to the original text if multiparser failed
// or `embeddedLanguageFormatting: "off"`
case "importExport":
- return concat$F([node.value, hardline$s]);
+ return [node.value, hardline$8];
+
+ case "esComment":
+ return ["{/* ", node.value, " */}"];
case "jsx":
return node.value;
case "math":
- return concat$F(["$$", hardline$s, node.value ? concat$F([concat$F(replaceEndOfLineWith$1(node.value, hardline$s)), hardline$s]) : "", "$$"]);
+ return ["$$", hardline$8, node.value ? [...replaceTextEndOfLine$7(node.value, hardline$8), hardline$8] : "", "$$"];
case "inlineMath":
{
// remark-math trims content but we don't want to remove whitespaces
// since it's very possible that it's recognized as math accidentally
- return options.originalText.slice(locStart$h(node), locEnd$n(node));
+ return options.originalText.slice(locStart$6(node), locEnd$5(node));
}
case "tableRow": // handled in "table"
@@ -51521,17 +54277,17 @@ function genericPrint$4(path, options, print) {
function printListItem(path, options, print, listPrefix) {
const node = path.getValue();
const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
- return concat$F([prefix, printChildren$1(path, options, print, {
+ return [prefix, printChildren$4(path, options, print, {
processor: (childPath, index) => {
if (index === 0 && childPath.getValue().type !== "list") {
- return align$5(" ".repeat(prefix.length), childPath.call(print));
+ return align$1(" ".repeat(prefix.length), print());
}
const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
- return concat$F([alignment, align$5(alignment, childPath.call(print))]);
+ return [alignment, align$1(alignment, print())];
}
- })]);
+ })];
}
function alignListPrefix(prefix, options) {
@@ -51550,8 +54306,6 @@ function getNthListSiblingIndex(node, parentNode) {
}
function getNthSiblingIndex(node, parentNode, condition) {
- condition = condition || (() => true);
-
let index = -1;
for (const childNode of parentNode.children) {
@@ -51567,8 +54321,8 @@ function getNthSiblingIndex(node, parentNode, condition) {
}
}
-function getAncestorCounter$1(path, typeOrTypes) {
- const types = [].concat(typeOrTypes);
+function getAncestorCounter(path, typeOrTypes) {
+ const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes];
let counter = -1;
let ancestorNode;
@@ -51581,28 +54335,27 @@ function getAncestorCounter$1(path, typeOrTypes) {
return -1;
}
-function getAncestorNode$2(path, typeOrTypes) {
- const counter = getAncestorCounter$1(path, typeOrTypes);
+function getAncestorNode(path, typeOrTypes) {
+ const counter = getAncestorCounter(path, typeOrTypes);
return counter === -1 ? null : path.getParentNode(counter);
}
function printLine(path, value, options) {
if (options.proseWrap === "preserve" && value === "\n") {
- return hardline$s;
+ return hardline$8;
}
- const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
- return value !== "" ? isBreakable ? line$n : " " : isBreakable ? softline$l : "";
+ const isBreakable = options.proseWrap === "always" && !getAncestorNode(path, SINGLE_LINE_NODE_TYPES);
+ return value !== "" ? isBreakable ? line$a : " " : isBreakable ? softline$6 : "";
}
function printTable(path, options, print) {
- const hardlineWithoutBreakParent = hardline$s.parts[0];
const node = path.getValue();
const columnMaxWidths = []; // { [rowIndex: number]: { [columnIndex: number]: {text: string, width: number} } }
const contents = path.map(rowPath => rowPath.map((cellPath, columnIndex) => {
- const text = printDocToString$3(cellPath.call(print), options).formatted;
- const width = getStringWidth$4(text);
+ const text = printDocToString(print(), options).formatted;
+ const width = getStringWidth(text);
columnMaxWidths[columnIndex] = Math.max(columnMaxWidths[columnIndex] || 3, // minimum width = 3 (---, :--, :-:, --:)
width);
return {
@@ -51615,24 +54368,24 @@ function printTable(path, options, print) {
false);
if (options.proseWrap !== "never") {
- return concat$F([breakParent$6, alignedTable]);
+ return [breakParent$4, alignedTable];
} // Only if the --prose-wrap never is set and it exceeds the print width.
const compactTable = printTableContents(
/* isCompact */
true);
- return concat$F([breakParent$6, group$t(ifBreak$h(compactTable, alignedTable))]);
+ return [breakParent$4, group$7(ifBreak$5(compactTable, alignedTable))];
function printTableContents(isCompact) {
/** @type{Doc[]} */
const parts = [printRow(contents[0], isCompact), printAlign(isCompact)];
if (contents.length > 1) {
- parts.push(join$k(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, isCompact))));
+ parts.push(join$7(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, isCompact))));
}
- return join$k(hardlineWithoutBreakParent, parts);
+ return join$7(hardlineWithoutBreakParent, parts);
}
function printAlign(isCompact) {
@@ -51683,8 +54436,9 @@ function printRoot(path, options, print) {
const {
children
} = path.getValue();
- children.forEach((childNode, index) => {
- switch (isPrettierIgnore(childNode)) {
+
+ for (const [index, childNode] of children.entries()) {
+ switch (isPrettierIgnore$2(childNode)) {
case "start":
if (ignoreStart === null) {
ignoreStart = {
@@ -51709,14 +54463,15 @@ function printRoot(path, options, print) {
break;
}
- });
- return printChildren$1(path, options, print, {
+ }
+
+ return printChildren$4(path, options, print, {
processor: (childPath, index) => {
- if (ignoreRanges.length !== 0) {
+ if (ignoreRanges.length > 0) {
const ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
- return concat$F([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
+ return [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) {
@@ -51729,16 +54484,17 @@ function printRoot(path, options, print) {
}
}
- return childPath.call(print);
+ return print();
}
});
}
-function printChildren$1(path, options, print, events) {
- events = events || {};
- const postprocessor = events.postprocessor || concat$F;
+function printChildren$4(path, options, print, events = {}) {
+ const {
+ postprocessor
+ } = events;
- const processor = events.processor || (childPath => childPath.call(print));
+ const processor = events.processor || (() => print());
const node = path.getValue();
const parts = [];
@@ -51755,22 +54511,22 @@ function printChildren$1(path, options, print, events) {
options
};
- if (!shouldNotPrePrintHardline(childNode, data)) {
- parts.push(hardline$s); // Can't find a case to pass `shouldPrePrintTripleHardline`
+ if (shouldPrePrintHardline(childNode, data)) {
+ parts.push(hardline$8); // Can't find a case to pass `shouldPrePrintTripleHardline`
/* istanbul ignore next */
if (lastChildNode && TRAILING_HARDLINE_NODES.has(lastChildNode.type)) {
if (shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$s);
+ parts.push(hardline$8);
}
} else {
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$s);
+ parts.push(hardline$8);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$s);
+ parts.push(hardline$8);
}
}
}
@@ -51779,14 +54535,14 @@ function printChildren$1(path, options, print, events) {
lastChildNode = childNode;
}
}, "children");
- return postprocessor(parts);
+ return postprocessor ? postprocessor(parts) : parts;
}
-function getLastDescendantNode(node) {
+function getLastDescendantNode$2(node) {
let current = node;
- while (current.children && current.children.length !== 0) {
- current = current.children[current.children.length - 1];
+ while (isNonEmptyArray$2(current.children)) {
+ current = getLast$3(current.children);
}
return current;
@@ -51794,20 +54550,33 @@ function getLastDescendantNode(node) {
/** @return {false | 'next' | 'start' | 'end'} */
-function isPrettierIgnore(node) {
- if (node.type !== "html") {
- return false;
+function isPrettierIgnore$2(node) {
+ let match;
+
+ if (node.type === "html") {
+ match = node.value.match(/^$/);
+ } else {
+ let comment;
+
+ if (node.type === "esComment") {
+ comment = node;
+ } else if (node.type === "paragraph" && node.children.length === 1 && node.children[0].type === "esComment") {
+ comment = node.children[0];
+ }
+
+ if (comment) {
+ match = comment.value.match(/^prettier-ignore(?:-(start|end))?$/);
+ }
}
- const match = node.value.match(/^$/);
- return match === null ? false : match[1] ? match[1] : "next";
+ return match ? match[1] ? match[1] : "next" : false;
}
-function shouldNotPrePrintHardline(node, data) {
+function shouldPrePrintHardline(node, data) {
const isFirstNode = data.parts.length === 0;
- const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
- const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
- return isFirstNode || isInlineNode || isInlineHTML;
+ const isInlineNode = INLINE_NODE_TYPES.includes(node.type);
+ const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.includes(data.parentNode.type);
+ return !isFirstNode && !isInlineNode && !isInlineHTML;
}
function shouldPrePrintDoubleHardline(node, data) {
@@ -51815,7 +54584,7 @@ function shouldPrePrintDoubleHardline(node, data) {
const isSiblingNode = isSequence && SIBLING_NODE_TYPES.has(node.type);
const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
- const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
+ const isPrevNodePrettierIgnore = isPrettierIgnore$2(data.prevNode) === "next";
const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
@@ -51828,20 +54597,22 @@ function shouldPrePrintTripleHardline(node, data) {
}
function shouldRemainTheSameContent(path) {
- const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
+ const ancestorNode = getAncestorNode(path, ["linkReference", "imageReference"]);
return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
}
+/**
+ * @param {string} url
+ * @param {string[] | string} [dangerousCharOrChars]
+ * @returns {string}
+ */
+
-function printUrl(url, dangerousCharOrChars) {
- const dangerousChars = [" "].concat(dangerousCharOrChars || []);
+function printUrl(url, dangerousCharOrChars = []) {
+ const dangerousChars = [" ", ...(Array.isArray(dangerousCharOrChars) ? dangerousCharOrChars : [dangerousCharOrChars])];
return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
}
-function printTitle(title, options, printSpace) {
- if (printSpace == null) {
- printSpace = true;
- }
-
+function printTitle(title, options, printSpace = true) {
if (!title) {
return "";
}
@@ -51871,41 +54642,59 @@ function clamp(value, min, max) {
}
function hasPrettierIgnore$5(path) {
- const index = +path.getName();
+ const index = Number(path.getName());
if (index === 0) {
return false;
}
const prevNode = path.getParentNode().children[index - 1];
- return isPrettierIgnore(prevNode) === "next";
+ return isPrettierIgnore$2(prevNode) === "next";
}
var printerMarkdown = {
- preprocess: printPreprocess$1,
- print: genericPrint$4,
- embed: embed_1$2,
- massageAstNode: clean_1$3,
+ preprocess: preprocess$4,
+ print: genericPrint$2,
+ embed: embed$5,
+ massageAstNode: clean$3,
hasPrettierIgnore: hasPrettierIgnore$5,
- insertPragma: insertPragma$6
+ insertPragma: insertPragma$4
};
+const commonOptions$2 = commonOptions$6; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
+
var options$5 = {
- proseWrap: commonOptions.proseWrap,
- singleQuote: commonOptions.singleQuote
+ proseWrap: commonOptions$2.proseWrap,
+ singleQuote: commonOptions$2.singleQuote
};
-var name$f = "Markdown";
-var type$d = "prose";
-var color$7 = "#083fa1";
-var aliases$4 = [
+var parsers$5 = {
+ /* istanbul ignore next */
+ get remark() {
+ return require("./parser-markdown.js").parsers.remark;
+ },
+
+ get markdown() {
+ return require("./parser-markdown.js").parsers.remark;
+ },
+
+ get mdx() {
+ return require("./parser-markdown.js").parsers.mdx;
+ }
+
+};
+
+var name$3 = "Markdown";
+var type$3 = "prose";
+var color$3 = "#083fa1";
+var aliases$2 = [
"pandoc"
];
-var aceMode$d = "markdown";
-var codemirrorMode$a = "gfm";
-var codemirrorMimeType$a = "text/x-gfm";
+var aceMode$3 = "markdown";
+var codemirrorMode$2 = "gfm";
+var codemirrorMimeType$2 = "text/x-gfm";
var wrap = true;
-var extensions$d = [
+var extensions$3 = [
".md",
".markdown",
".mdown",
@@ -51915,35 +54704,40 @@ var extensions$d = [
".mkdn",
".mkdown",
".ronn",
+ ".scd",
".workbook"
];
-var filenames$3 = [
+var filenames$1 = [
"contents.lr"
];
-var tmScope$d = "source.gfm";
-var languageId$d = 222;
-var require$$0$6 = {
- name: name$f,
- type: type$d,
- color: color$7,
- aliases: aliases$4,
- aceMode: aceMode$d,
- codemirrorMode: codemirrorMode$a,
- codemirrorMimeType: codemirrorMimeType$a,
+var tmScope$3 = "source.gfm";
+var languageId$3 = 222;
+var require$$4$3 = {
+ name: name$3,
+ type: type$3,
+ color: color$3,
+ aliases: aliases$2,
+ aceMode: aceMode$3,
+ codemirrorMode: codemirrorMode$2,
+ codemirrorMimeType: codemirrorMimeType$2,
wrap: wrap,
- extensions: extensions$d,
- filenames: filenames$3,
- tmScope: tmScope$d,
- languageId: languageId$d
+ extensions: extensions$3,
+ filenames: filenames$1,
+ tmScope: tmScope$3,
+ languageId: languageId$3
};
-const languages$4 = [createLanguage(require$$0$6, data => ({
+const createLanguage$2 = createLanguage$7;
+const printer$2 = printerMarkdown;
+const options$4 = options$5;
+const parsers$4 = parsers$5;
+const languages$3 = [createLanguage$2(require$$4$3, data => ({
since: "1.8.0",
parsers: ["markdown"],
vscodeLanguageIds: ["markdown"],
- filenames: data.filenames.concat(["README"]),
+ filenames: [...data.filenames, "README"],
extensions: data.extensions.filter(extension => extension !== ".mdx")
-})), createLanguage(require$$0$6, () => ({
+})), createLanguage$2(require$$4$3, () => ({
name: "MDX",
since: "1.15.0",
parsers: ["mdx"],
@@ -51951,43 +54745,28 @@ const languages$4 = [createLanguage(require$$0$6, data => ({
filenames: [],
extensions: [".mdx"]
}))];
-const printers$4 = {
- mdast: printerMarkdown
-};
-const parsers$4 = {
- /* istanbul ignore next */
- get remark() {
- return require("./parser-markdown").parsers.remark;
- },
-
- get markdown() {
- return require("./parser-markdown").parsers.remark;
- },
-
- get mdx() {
- return require("./parser-markdown").parsers.mdx;
- }
-
+const printers$1 = {
+ mdast: printer$2
};
var languageMarkdown = {
- languages: languages$4,
- options: options$5,
- printers: printers$4,
+ languages: languages$3,
+ options: options$4,
+ printers: printers$1,
parsers: parsers$4
};
const {
- isFrontMatterNode: isFrontMatterNode$4
-} = util;
-const ignoredProperties$4 = new Set(["sourceSpan", "startSourceSpan", "endSourceSpan", "nameSpan", "valueSpan"]);
+ isFrontMatterNode: isFrontMatterNode$1
+} = util$8;
+const ignoredProperties = new Set(["sourceSpan", "startSourceSpan", "endSourceSpan", "nameSpan", "valueSpan"]);
-function clean$6(ast, newNode) {
+function clean$2(ast, newNode) {
if (ast.type === "text" || ast.type === "comment") {
return null;
} // may be formatted by multiparser
- if (isFrontMatterNode$4(ast) || ast.type === "yaml" || ast.type === "toml") {
+ if (isFrontMatterNode$1(ast) || ast.type === "yaml" || ast.type === "toml") {
return null;
}
@@ -52000,10 +54779,10 @@ function clean$6(ast, newNode) {
}
}
-clean$6.ignoredProperties = ignoredProperties$4;
-var clean_1$4 = clean$6;
+clean$2.ignoredProperties = ignoredProperties;
+var clean_1 = clean$2;
-var htmlTagNames = [
+var require$$0 = [
"a",
"abbr",
"acronym",
@@ -52276,10 +55055,10 @@ var colgroup = [
"valign",
"width"
];
-var data$2 = [
+var data = [
"value"
];
-var del$1 = [
+var del = [
"cite",
"datetime"
];
@@ -52301,7 +55080,7 @@ var div = [
var dl = [
"compact"
];
-var embed$3 = [
+var embed$4 = [
"height",
"src",
"type",
@@ -52369,7 +55148,7 @@ var hr = [
"size",
"width"
];
-var html$1 = [
+var html = [
"manifest",
"version"
];
@@ -52472,7 +55251,7 @@ var li = [
"type",
"value"
];
-var link$3 = [
+var link = [
"as",
"charset",
"color",
@@ -52493,7 +55272,7 @@ var link$3 = [
"title",
"type"
];
-var map$1 = [
+var map = [
"name"
];
var menu = [
@@ -52514,7 +55293,7 @@ var meter = [
"optimum",
"value"
];
-var object$1 = [
+var object = [
"align",
"archive",
"border",
@@ -52602,7 +55381,7 @@ var select = [
var slot = [
"name"
];
-var source$2 = [
+var source = [
"media",
"sizes",
"src",
@@ -52728,7 +55507,7 @@ var video = [
"src",
"width"
];
-var htmlElementAttributes = {
+var require$$1 = {
"*": [
"accesskey",
"autocapitalize",
@@ -52772,15 +55551,15 @@ var htmlElementAttributes = {
caption: caption,
col: col,
colgroup: colgroup,
- data: data$2,
- del: del$1,
+ data: data,
+ del: del,
details: details,
dfn: dfn,
dialog: dialog,
dir: dir,
div: div,
dl: dl,
- embed: embed$3,
+ embed: embed$4,
fieldset: fieldset,
font: font,
form: form,
@@ -52794,7 +55573,7 @@ var htmlElementAttributes = {
h6: h6,
head: head,
hr: hr,
- html: html$1,
+ html: html,
iframe: iframe,
img: img,
input: input,
@@ -52803,12 +55582,12 @@ var htmlElementAttributes = {
label: label,
legend: legend,
li: li,
- link: link$3,
- map: map$1,
+ link: link,
+ map: map,
menu: menu,
meta: meta,
meter: meter,
- object: object$1,
+ object: object,
ol: ol,
optgroup: optgroup,
option: option,
@@ -52821,7 +55600,7 @@ var htmlElementAttributes = {
script: script,
select: select,
slot: slot,
- source: source$2,
+ source: source,
style: style,
table: table,
tbody: tbody,
@@ -52837,7 +55616,7 @@ var htmlElementAttributes = {
video: video
};
-var json$1 = {
+var require$$4$2 = {
"CSS_DISPLAY_TAGS": {
"area": "none",
"base": "none",
@@ -52933,16 +55712,34 @@ var json$1 = {
"CSS_WHITE_SPACE_DEFAULT": "normal"
};
+/**
+ * @typedef {import("../common/ast-path")} AstPath
+ */
+
+
+const htmlTagNames = require$$0;
+const htmlElementAttributes = require$$1;
const {
- inferParserByLanguage: inferParserByLanguage$2,
- isFrontMatterNode: isFrontMatterNode$5
-} = util;
+ inferParserByLanguage,
+ isFrontMatterNode
+} = util$8;
+const {
+ builders: {
+ line: line$9,
+ hardline: hardline$7,
+ join: join$6
+ },
+ utils: {
+ getDocParts: getDocParts$3,
+ replaceTextEndOfLine: replaceTextEndOfLine$6
+ }
+} = require$$7$3;
const {
CSS_DISPLAY_TAGS,
CSS_DISPLAY_DEFAULT,
CSS_WHITE_SPACE_TAGS,
CSS_WHITE_SPACE_DEFAULT
-} = json$1;
+} = require$$4$2;
const HTML_TAGS = arrayToMap(htmlTagNames);
const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes, arrayToMap); // https://infra.spec.whatwg.org/#ascii-whitespace
@@ -52952,18 +55749,18 @@ const htmlTrimStart = string => string.replace(/^[\t\n\f\r ]+/, "");
const htmlTrimEnd = string => string.replace(/[\t\n\f\r ]+$/, "");
-const htmlTrim = string => htmlTrimStart(htmlTrimEnd(string));
+const htmlTrim$1 = string => htmlTrimStart(htmlTrimEnd(string));
const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, "");
-const htmlTrimPreserveIndentation = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string));
+const htmlTrimPreserveIndentation$1 = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string));
const splitByHtmlWhitespace = string => string.split(/[\t\n\f\r ]+/);
const getLeadingHtmlWhitespace = string => string.match(/^[\t\n\f\r ]*/)[0];
-const getLeadingAndTrailingHtmlWhitespace = string => {
- const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)([\S\s]*?)([\t\n\f\r ]*)$/);
+const getLeadingAndTrailingHtmlWhitespace$1 = string => {
+ const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)(.*?)([\t\n\f\r ]*)$/s);
return {
leadingWhitespace,
trailingWhitespace,
@@ -52971,7 +55768,7 @@ const getLeadingAndTrailingHtmlWhitespace = string => {
};
};
-const hasHtmlWhitespace = string => /[\t\n\f\r ]/.test(string);
+const hasHtmlWhitespace$1 = string => /[\t\n\f\r ]/.test(string);
function arrayToMap(array) {
const map = Object.create(null);
@@ -52986,14 +55783,14 @@ function arrayToMap(array) {
function mapObject(object, fn) {
const newObject = Object.create(null);
- for (const key of Object.keys(object)) {
- newObject[key] = fn(object[key], key);
+ for (const [key, value] of Object.entries(object)) {
+ newObject[key] = fn(value, key);
}
return newObject;
}
-function shouldPreserveContent(node, options) {
+function shouldPreserveContent$2(node, options) {
// unterminated node in ie conditional comment
// e.g.
if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
@@ -53007,18 +55804,18 @@ function shouldPreserveContent(node, options) {
} // TODO: handle non-text children in
- if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
+ if (isPreLikeNode$1(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
return true;
}
- if (isVueNonHtmlBlock(node, options) && !isScriptLikeTag(node) && node.type !== "interpolation") {
+ if (isVueNonHtmlBlock$1(node, options) && !isScriptLikeTag$2(node) && node.type !== "interpolation") {
return true;
}
return false;
}
-function hasPrettierIgnore$6(node) {
+function hasPrettierIgnore$4(node) {
/* istanbul ignore next */
if (node.type === "attribute") {
return false;
@@ -53041,44 +55838,30 @@ function hasPrettierIgnore$6(node) {
function isPrettierIgnore$1(node) {
return node.type === "comment" && node.value.trim() === "prettier-ignore";
}
-
-function getPrettierIgnoreAttributeCommentData(value) {
- const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
-
- if (!match) {
- return false;
- }
-
- if (!match[1]) {
- return true;
- }
-
- return match[1].split(/\s+/);
-}
/** there's no opening/closing tag or it's considered not breakable */
-function isTextLikeNode(node) {
+function isTextLikeNode$2(node) {
return node.type === "text" || node.type === "comment";
}
-function isScriptLikeTag(node) {
+function isScriptLikeTag$2(node) {
return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
}
-function canHaveInterpolation(node) {
- return node.children && !isScriptLikeTag(node);
+function canHaveInterpolation$1(node) {
+ return node.children && !isScriptLikeTag$2(node);
}
-function isWhitespaceSensitiveNode(node) {
- return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
+function isWhitespaceSensitiveNode$1(node) {
+ return isScriptLikeTag$2(node) || node.type === "interpolation" || isIndentationSensitiveNode$1(node);
}
-function isIndentationSensitiveNode(node) {
+function isIndentationSensitiveNode$1(node) {
return getNodeCssStyleWhiteSpace(node).startsWith("pre");
}
-function isLeadingSpaceSensitiveNode(node, options) {
+function isLeadingSpaceSensitiveNode$1(node, options) {
const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
@@ -53088,7 +55871,7 @@ function isLeadingSpaceSensitiveNode(node, options) {
return isLeadingSpaceSensitive;
function _isLeadingSpaceSensitiveNode() {
- if (isFrontMatterNode$5(node)) {
+ if (isFrontMatterNode(node)) {
return false;
}
@@ -53100,11 +55883,11 @@ function isLeadingSpaceSensitiveNode(node, options) {
return false;
}
- if (isPreLikeNode(node.parent)) {
+ if (isPreLikeNode$1(node.parent)) {
return true;
}
- if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
+ if (!node.prev && (node.parent.type === "root" || isPreLikeNode$1(node) && node.parent || isScriptLikeTag$2(node.parent) || isVueCustomBlock$1(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
return false;
}
@@ -53116,8 +55899,8 @@ function isLeadingSpaceSensitiveNode(node, options) {
}
}
-function isTrailingSpaceSensitiveNode(node, options) {
- if (isFrontMatterNode$5(node)) {
+function isTrailingSpaceSensitiveNode$1(node, options) {
+ if (isFrontMatterNode(node)) {
return false;
}
@@ -53129,11 +55912,11 @@ function isTrailingSpaceSensitiveNode(node, options) {
return false;
}
- if (isPreLikeNode(node.parent)) {
+ if (isPreLikeNode$1(node.parent)) {
return true;
}
- if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
+ if (!node.next && (node.parent.type === "root" || isPreLikeNode$1(node) && node.parent || isScriptLikeTag$2(node.parent) || isVueCustomBlock$1(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
return false;
}
@@ -53144,27 +55927,27 @@ function isTrailingSpaceSensitiveNode(node, options) {
return true;
}
-function isDanglingSpaceSensitiveNode(node) {
- return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
+function isDanglingSpaceSensitiveNode$1(node) {
+ return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag$2(node);
}
-function forceNextEmptyLine(node) {
- return isFrontMatterNode$5(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
+function forceNextEmptyLine$1(node) {
+ return isFrontMatterNode(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
}
/** firstChild leadingSpaces and lastChild trailingSpaces */
-function forceBreakContent(node) {
- return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
+function forceBreakContent$1(node) {
+ return forceBreakChildren$1(node) || node.type === "element" && node.children.length > 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
}
/** spaces between children */
-function forceBreakChildren(node) {
- return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
+function forceBreakChildren$1(node) {
+ return node.type === "element" && node.children.length > 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
}
-function preferHardlineAsLeadingSpaces(node) {
+function preferHardlineAsLeadingSpaces$1(node) {
return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
}
@@ -53198,8 +55981,8 @@ function preferHardlineAsSurroundingSpaces(node) {
return false;
}
-function getLastDescendant(node) {
- return node.lastChild ? getLastDescendant(node.lastChild) : node;
+function getLastDescendant$1(node) {
+ return node.lastChild ? getLastDescendant$1(node.lastChild) : node;
}
function hasNonTextChild(node) {
@@ -53255,7 +56038,7 @@ function inferStyleParser(node) {
}
}
-function inferScriptParser(node, options) {
+function inferScriptParser$1(node, options) {
if (node.name === "script" && !node.attrMap.src) {
if (!node.attrMap.lang && !node.attrMap.type) {
return "babel";
@@ -53268,8 +56051,8 @@ function inferScriptParser(node, options) {
return inferStyleParser(node);
}
- if (options && isVueNonHtmlBlock(node, options)) {
- return _inferScriptParser(node) || !("src" in node.attrMap) && inferParserByLanguage$2(node.attrMap.lang, options);
+ if (options && isVueNonHtmlBlock$1(node, options)) {
+ return _inferScriptParser(node) || !("src" in node.attrMap) && inferParserByLanguage(node.attrMap.lang, options);
}
}
@@ -53297,11 +56080,16 @@ function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
}
-function isPreLikeNode(node) {
+function isPreLikeNode$1(node) {
return getNodeCssStyleWhiteSpace(node).startsWith("pre");
}
+/**
+ * @param {AstPath} path
+ * @param {(any) => boolean} predicate
+ */
+
-function countParents(path, predicate) {
+function countParents$1(path, predicate) {
let counter = 0;
for (let i = path.stack.length - 1; i >= 0; i--) {
@@ -53329,7 +56117,7 @@ function hasParent(node, fn) {
return false;
}
-function getNodeCssStyleDisplay(node, options) {
+function getNodeCssStyleDisplay$1(node, options) {
if (node.prev && node.prev.type === "comment") {
//
const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
@@ -53377,7 +56165,7 @@ function getNodeCssStyleWhiteSpace(node) {
}
function getMinIndentation(text) {
- let minIndentation = Infinity;
+ let minIndentation = Number.POSITIVE_INFINITY;
for (const lineText of text.split("\n")) {
if (lineText.length === 0) {
@@ -53399,18 +56187,14 @@ function getMinIndentation(text) {
}
}
- return minIndentation === Infinity ? 0 : minIndentation;
+ return minIndentation === Number.POSITIVE_INFINITY ? 0 : minIndentation;
}
-function dedentString(text, minIndent = getMinIndentation(text)) {
+function dedentString$1(text, minIndent = getMinIndentation(text)) {
return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
}
-function shouldNotPrintClosingTag(node, options) {
- return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$6(node) || shouldPreserveContent(node.parent, options));
-}
-
-function countChars(text, char) {
+function countChars$1(text, char) {
let counter = 0;
for (let i = 0; i < text.length; i++) {
@@ -53422,7 +56206,7 @@ function countChars(text, char) {
return counter;
}
-function unescapeQuoteEntities(text) {
+function unescapeQuoteEntities$2(text) {
return text.replace(/'/g, "'").replace(/"/g, '"');
} // top-level elements (excluding ,