Migrate src/{main,common,config}/** to ES Modules (#12344)

This commit is contained in:
fisker Cheung authored and GitHub committed 2022-02-23 20:16:30 +08:00
1 parent dceb88bb3b
commit 05aa5e16d6
47 files changed
+266 -313

No files matched your search

-3
View File
@@ -176,10 +176,7 @@ module.exports = {
{
files: [
"**/*.cjs",
"src/common/**/*.js",
"src/config/**/*.js",
"src/document/**/*.js",
"src/main/**/*.js",
"src/utils/**/*.js",
"scripts/tools/eslint-plugin-prettier-internal-rules/**/*.js",
"website/**/*.js",
+5
View File
@@ -77,6 +77,11 @@ function* getEsbuildOptions(bundle, buildOptions) {
};
}
}
// Use `__dirname` directly
replaceStrings[
"const __dirname = path.dirname(fileURLToPath(import.meta.url));"
] = "";
} else {
// Universal bundle only use version info from package.json
// Replace package.json with `{version: "{VERSION}"}`
+2 -1
View File
@@ -214,7 +214,8 @@ const coreBundles = [
external: ["benchmark"],
},
{
input: "src/common/third-party.js",
input: "src/common/third-party.cjs",
output: "third-party.js",
replace: {
// cosmiconfig@6 -> import-fresh can't find parentModule, since module is bundled
"parentModule(__filename)": "__filename",
+1 -1
View File
@@ -2,7 +2,7 @@ import { promises as fs } from "fs";
import path from "path";
import chalk from "chalk";
import prettier from "../index.js";
import thirdParty from "../common/third-party.js";
import thirdParty from "../common/third-party.cjs";
import prettierInternal from "./prettier-internal.js";
import { expandPatterns, fixWindowsSlashes } from "./expand-patterns.js";
import getOptionsForFile from "./options/get-options-for-file.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import thirdParty from "../common/third-party.js";
import thirdParty from "../common/third-party.cjs";
// Some CI pipelines incorrectly report process.stdout.isTTY status,
// which causes unwanted lines in the output. An additional check for isCI() helps.
+2 -3
View File
@@ -1,5 +1,4 @@
"use strict";
const getLast = require("../utils/get-last.js");
import getLast from "../utils/get-last.js";
function getNodeHelper(path, count) {
const stackIndex = getNodeStackIndexHelper(path.stack, count);
@@ -194,4 +193,4 @@ class AstPath {
}
}
module.exports = AstPath;
export default AstPath;
+3 -3
View File
@@ -1,9 +1,7 @@
"use strict";
const CATEGORY_COMMON = "Common";
// format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
module.exports = {
const options = {
bracketSpacing: {
since: "0.0.0",
category: CATEGORY_COMMON,
@@ -62,3 +60,5 @@ module.exports = {
description: "Enforce single attribute per line in HTML, Vue and JSX.",
},
};
export default options;
+4 -6
View File
@@ -1,8 +1,6 @@
"use strict";
const path = require("path");
const ignore = require("ignore");
const getFileContentOrNull = require("../utils/get-file-content-or-null.js");
import path from "path";
import ignore from "ignore";
import getFileContentOrNull from "../utils/get-file-content-or-null.js";
/**
* @param {string?} ignorePath
@@ -39,4 +37,4 @@ function _createIgnorer(ignoreContent, withNodeModules) {
return ignorer;
}
module.exports = createIgnorer;
export default createIgnorer;
+54
View File
@@ -0,0 +1,54 @@
// cjs version for ../doc to use
"use strict";
function guessEndOfLine(text) {
const index = text.indexOf("\r");
if (index >= 0) {
return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
}
return "lf";
}
function convertEndOfLineToChars(value) {
switch (value) {
case "cr":
return "\r";
case "crlf":
return "\r\n";
default:
return "\n";
}
}
function countEndOfLineChars(text, eol) {
let regex;
switch (eol) {
case "\n":
regex = /\n/g;
break;
case "\r":
regex = /\r/g;
break;
case "\r\n":
regex = /\r\n/g;
break;
default:
/* istanbul ignore next */
throw new Error(`Unexpected "eol" ${JSON.stringify(eol)}.`);
}
const endOfLines = text.match(regex);
return endOfLines ? endOfLines.length : 0;
}
function normalizeEndOfLine(text) {
return text.replace(/\r\n?/g, "\n");
}
module.exports = {
guessEndOfLine,
convertEndOfLineToChars,
countEndOfLineChars,
normalizeEndOfLine,
};
+1 -3
View File
@@ -1,5 +1,3 @@
"use strict";
function guessEndOfLine(text) {
const index = text.indexOf("\r");
if (index >= 0) {
@@ -45,7 +43,7 @@ function normalizeEndOfLine(text) {
return text.replace(/\r\n?/g, "\n");
}
module.exports = {
export {
guessEndOfLine,
convertEndOfLineToChars,
countEndOfLineChars,
+1 -8
View File
@@ -1,13 +1,6 @@
"use strict";
class ConfigError extends Error {}
class DebugError extends Error {}
class UndefinedParserError extends Error {}
class ArgExpansionBailout extends Error {}
module.exports = {
ConfigError,
DebugError,
UndefinedParserError,
ArgExpansionBailout,
};
export { ConfigError, DebugError, UndefinedParserError, ArgExpansionBailout };
+6 -8
View File
@@ -1,9 +1,7 @@
"use strict";
const path = require("path");
const options = require("../main/options.js");
const config = require("../config/resolve-config.js");
const createIgnorer = require("./create-ignorer.js");
import path from "path";
import { inferParser } from "../main/options.js";
import * as config from "../config/resolve-config.js";
import createIgnorer from "./create-ignorer.js";
/**
* @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
@@ -65,7 +63,7 @@ function getFileParser(resolvedConfig, filePath, plugins) {
return resolvedConfig.parser;
}
const inferredParser = options.inferParser(filePath, plugins);
const inferredParser = inferParser(filePath, plugins);
if (inferredParser) {
return inferredParser;
@@ -120,4 +118,4 @@ function normalizeFilePath(filePath, ignorePath) {
: filePath;
}
module.exports = getFileInfo;
export default getFileInfo;
+13 -13
View File
@@ -1,13 +1,16 @@
"use strict";
import { createRequire } from "module";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import uniqBy from "lodash/uniqBy.js";
import partition from "lodash/partition.js";
import fastGlob from "fast-glob";
import mem, { memClear } from "mem";
import thirdParty from "./third-party.cjs";
import resolve from "./resolve.js";
const fs = require("fs");
const path = require("path");
const uniqBy = require("lodash/uniqBy.js");
const partition = require("lodash/partition.js");
const fastGlob = require("fast-glob");
const { default: mem, memClear } = require("../../vendors/mem.js");
const thirdParty = require("./third-party.js");
const resolve = require("./resolve.js");
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const memoizedLoad = mem(load, { cacheKey: JSON.stringify });
const memoizedSearch = mem(findPluginsInNodeModules);
@@ -125,7 +128,4 @@ function isDirectory(dir) {
}
}
module.exports = {
loadPlugins: memoizedLoad,
clearCache,
};
export { memoizedLoad as loadPlugins, clearCache };
-5
View File
@@ -1,5 +0,0 @@
{
"//TODO": "Remove this file when we close #10157",
"type": "commonjs",
"description": "A package.json file to use `.js` files in this directory as CommonJS module."
}
+1 -3
View File
@@ -1,5 +1,3 @@
"use strict";
function createError(message, loc) {
// Construct an error similar to the ones thrown by Babel.
const error = new SyntaxError(
@@ -10,4 +8,4 @@ function createError(message, loc) {
return error;
}
module.exports = createError;
export default createError;
+4 -2
View File
@@ -1,4 +1,6 @@
"use strict";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
let { resolve } = require;
@@ -15,4 +17,4 @@ if (resolve.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) {
};
}
module.exports = resolve;
export default resolve;
File renamed without changes.
+2 -30
View File
@@ -1,6 +1,4 @@
"use strict";
const {
export {
getMaxContinuousCount,
getStringWidth,
getAlignmentSize,
@@ -24,30 +22,4 @@ const {
addLeadingComment,
addDanglingComment,
addTrailingComment,
} = require("./util.js");
module.exports = {
getMaxContinuousCount,
getStringWidth,
getAlignmentSize,
getIndentSize,
skip,
skipWhitespace,
skipSpaces,
skipNewline,
skipToLineEnd,
skipEverythingButNewLine,
skipInlineComment,
skipTrailingComment,
hasNewline,
hasNewlineInRange,
hasSpaces,
isNextLineEmpty,
isNextLineEmptyAfterIndex,
isPreviousLineEmpty,
getNextNonSpaceNonCommentCharacterIndex,
makeString,
addLeadingComment,
addDanglingComment,
addTrailingComment,
};
} from "./util.js";
+12 -14
View File
@@ -1,20 +1,18 @@
"use strict";
const escapeStringRegexp = require("escape-string-regexp");
const getLast = require("../utils/get-last.js");
const { getSupportInfo } = require("../main/support.js");
const isNonEmptyArray = require("../utils/is-non-empty-array.js");
const getStringWidth = require("../utils/get-string-width.js");
const {
import escapeStringRegexp from "escape-string-regexp";
import getLast from "../utils/get-last.js";
import { getSupportInfo } from "../main/support.js";
import isNonEmptyArray from "../utils/is-non-empty-array.js";
import getStringWidth from "../utils/get-string-width.js";
import {
skipWhitespace,
skipSpaces,
skipToLineEnd,
skipEverythingButNewLine,
} = require("../utils/text/skip.js");
const skipInlineComment = require("../utils/text/skip-inline-comment.js");
const skipTrailingComment = require("../utils/text/skip-trailing-comment.js");
const skipNewline = require("../utils/text/skip-newline.js");
const getNextNonSpaceNonCommentCharacterIndexWithStartIndex = require("../utils/text/get-next-non-space-non-comment-character-index-with-start-index.js");
} from "../utils/text/skip.js";
import skipInlineComment from "../utils/text/skip-inline-comment.js";
import skipTrailingComment from "../utils/text/skip-trailing-comment.js";
import skipNewline from "../utils/text/skip-newline.js";
import getNextNonSpaceNonCommentCharacterIndexWithStartIndex from "../utils/text/get-next-non-space-non-comment-character-index-with-start-index.js";
const getPenultimate = (arr) => arr[arr.length - 2];
@@ -479,7 +477,7 @@ function describeNodeForDebugging(node) {
return nodeType + (nodeName ? " " + nodeName : "");
}
module.exports = {
export {
inferParserByLanguage,
getStringWidth,
getMaxContinuousCount,
+3 -5
View File
@@ -1,10 +1,8 @@
"use strict";
// Simple version of `find-project-root`
// https://github.com/kirstein/find-project-root/blob/master/index.js
const fs = require("fs");
const path = require("path");
import fs from "fs";
import path from "path";
const MARKERS = [".git", ".hg"];
@@ -23,4 +21,4 @@ function findProjectRoot(directory) {
return directory;
}
module.exports = findProjectRoot;
export default findProjectRoot;
-5
View File
@@ -1,5 +0,0 @@
{
"//TODO": "Remove this file when we close #10157",
"type": "commonjs",
"description": "A package.json file to use `.js` files in this directory as CommonJS module."
}
+6 -11
View File
@@ -1,11 +1,9 @@
"use strict";
import path from "path";
const path = require("path");
const editorconfig = require("editorconfig");
const editorConfigToPrettier = require("editorconfig-to-prettier");
const { default: mem, memClear } = require("../../vendors/mem.js");
const findProjectRoot = require("./find-project-root.js");
import editorconfig from "editorconfig";
import editorConfigToPrettier from "editorconfig-to-prettier";
import mem, { memClear } from "mem";
import findProjectRoot from "./find-project-root.js";
const jsonStringifyMem = (fn) => mem(fn, { cacheKey: JSON.stringify });
@@ -40,7 +38,4 @@ function clearCache() {
memClear(editorconfigAsyncWithCache);
}
module.exports = {
getLoadFunction,
clearCache,
};
export { getLoadFunction, clearCache };
+11 -15
View File
@@ -1,14 +1,13 @@
"use strict";
import { createRequire } from "module";
import path from "path";
import micromatch from "micromatch";
import mem, { memClear } from "mem";
import thirdParty from "../common/third-party.cjs";
const path = require("path");
const micromatch = require("micromatch");
const thirdParty = require("../common/third-party.js");
const loadToml = require("../utils/load-toml.js");
const loadJson5 = require("../utils/load-json5.js");
const resolve = require("../common/resolve.js");
const { default: mem, memClear } = require("../../vendors/mem.js");
const resolveEditorConfig = require("./resolve-config-editorconfig.js");
import loadToml from "../utils/load-toml.js";
import loadJson5 from "../utils/load-json5.js";
import resolve from "../common/resolve.js";
import * as resolveEditorConfig from "./resolve-config-editorconfig.js";
/**
* @typedef {import("cosmiconfig/dist/Explorer").Explorer} Explorer
@@ -20,6 +19,7 @@ const resolveEditorConfig = require("./resolve-config-editorconfig.js");
*/
const getExplorerMemoized = mem(
(opts) => {
const require = createRequire(import.meta.url);
const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")];
const explorer = cosmiconfig("prettier", {
cache: opts.cache,
@@ -192,8 +192,4 @@ function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
);
}
module.exports = {
resolveConfig,
resolveConfigFile,
clearCache,
};
export { resolveConfig, resolveConfigFile, clearCache };
+1 -1
View File
@@ -1,6 +1,6 @@
"use strict";
const { convertEndOfLineToChars } = require("../common/end-of-line.js");
const { convertEndOfLineToChars } = require("../common/end-of-line.cjs");
const getLast = require("../utils/get-last.js");
const getStringWidth = require("../utils/get-string-width.js");
const { fill, cursor, indent } = require("./doc-builders.js");
+32 -16
View File
@@ -2,12 +2,28 @@ import { createRequire } from "module";
import core from "./main/core.js";
import { getSupportInfo } from "./main/support.js";
import getFileInfo from "./common/get-file-info.js";
import sharedUtil from "./common/util-shared.js";
import plugins from "./common/load-plugins.js";
import config from "./config/resolve-config.js";
import * as sharedUtil from "./common/util-shared.js";
import {
loadPlugins,
clearCache as clearPluginCache,
} from "./common/load-plugins.js";
import {
resolveConfig,
resolveConfigFile,
clearCache as clearConfigCache,
} from "./config/resolve-config.js";
import doc from "./document/index.js";
import languages from "./languages.js";
import * as errors from "./common/errors.js";
import * as coreOptions from "./main/core-options.js";
import createIgnorer from "./common/create-ignorer.js";
import * as optionsModule from "./main/options.js";
import * as optionsNormalizer from "./main/options-normalizer.js";
import arrayify from "./utils/arrayify.js";
import getLast from "./utils/get-last.js";
import { isNonEmptyArray } from "./common/util.js";
const require = createRequire(import.meta.url);
const { version } = require("../package.json");
@@ -22,7 +38,7 @@ function _withPlugins(
...opts,
plugins: [
...languages,
...plugins.loadPlugins(opts.plugins, opts.pluginSearchDirs),
...loadPlugins(opts.plugins, opts.pluginSearchDirs),
],
};
return fn(...args);
@@ -54,11 +70,11 @@ const prettier = {
doc,
resolveConfig: config.resolveConfig,
resolveConfigFile: config.resolveConfigFile,
resolveConfig,
resolveConfigFile,
clearConfigCache() {
config.clearCache();
plugins.clearCache();
clearConfigCache();
clearPluginCache();
},
/** @type {typeof getFileInfo} */
@@ -72,15 +88,15 @@ const prettier = {
// Internal shared
__internal: {
errors: require("./common/errors.js"),
coreOptions: require("./main/core-options.js"),
createIgnorer: require("./common/create-ignorer.js"),
optionsModule: require("./main/options.js"),
optionsNormalizer: require("./main/options-normalizer.js"),
errors,
coreOptions,
createIgnorer,
optionsModule,
optionsNormalizer,
utils: {
arrayify: require("./utils/arrayify.js"),
getLast: require("./utils/get-last.js"),
isNonEmptyArray: require("./common/util.js").isNonEmptyArray,
arrayify,
getLast,
isNonEmptyArray,
},
},
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @typedef {import("../../common/ast-path")} AstPath
* @typedef {import("../../common/ast-path.js").default} AstPath
*/
import { inferParserByLanguage, isFrontMatterNode } from "../../common/util.js";
+1 -1
View File
@@ -33,7 +33,7 @@ import isBlockComment from "./utils/is-block-comment.js";
/**
* @typedef {import("./types/estree").Node} Node
* @typedef {import("./types/estree").Comment} Comment
* @typedef {import("../common/ast-path")} AstPath
* @typedef {import("../common/ast-path.js").default} AstPath
*
* @typedef {Object} CommentContext
* @property {Comment} comment
-33
View File
@@ -1,33 +0,0 @@
// A cjs version of loc.js to use in `../main/parser.js`
"use strict";
const isNonEmptyArray = require("../utils/is-non-empty-array.js");
/**
* @typedef {import("./types/estree").Node} Node
*/
function locStart(node, opts) {
const { ignoreDecorators } = opts || {};
// Handle nodes with decorators. They should start at the first decorator
if (!ignoreDecorators) {
const decorators =
(node.declaration && node.declaration.decorators) || node.decorators;
if (isNonEmptyArray(decorators)) {
return locStart(decorators[0]);
}
}
return node.range ? node.range[0] : node.start;
}
function locEnd(node) {
return node.range ? node.range[1] : node.end;
}
module.exports = {
locStart,
locEnd,
};
+1 -1
View File
@@ -6,7 +6,7 @@ const {
builders: { join, line, group },
} = doc;
/** @typedef {import("../../common/ast-path")} AstPath */
/** @typedef {import("../../common/ast-path.js").default} AstPath */
function printAngular(path, options, print) {
const node = path.getValue();
+1 -1
View File
@@ -36,7 +36,7 @@ const isEmptyStringOrAnyLine = (doc) =>
doc === "" || doc === line || doc === hardline || doc === softline;
/**
* @typedef {import("../../common/ast-path")} AstPath
* @typedef {import("../../common/ast-path.js").default} AstPath
* @typedef {import("../types/estree").Node} Node
* @typedef {import("../types/estree").JSXElement} JSXElement
*/
+1 -1
View File
@@ -24,7 +24,7 @@ const {
/**
* @typedef {import("../../document").Doc} Doc
* @typedef {import("../../common/ast-path")} AstPath
* @typedef {import("../../common/ast-path.js").default} AstPath
*
* @typedef {any} Options - Prettier options (TBD ...)
*/
+1 -1
View File
@@ -26,7 +26,7 @@ const isIdentifierName = esutils.keyword.isIdentifierNameES5;
* @typedef {import("../types/estree").TaggedTemplateExpression} TaggedTemplateExpression
* @typedef {import("../types/estree").Literal} Literal
*
* @typedef {import("../../common/ast-path")} AstPath
* @typedef {import("../../common/ast-path.js").default} AstPath
*/
// We match any whitespace except line terminators because
+7 -7
View File
@@ -1,12 +1,12 @@
"use strict";
import AstPath from "../common/ast-path.js";
import doc from "../document/index.js";
import { printComments } from "./comments.js";
import { printSubtree } from "./multiparser.js";
const AstPath = require("../common/ast-path.js");
const {
builders: { hardline, addAlignmentToDoc },
utils: { propagateBreaks },
} = require("../document/index.js");
const { printComments } = require("./comments.js");
const multiparser = require("./multiparser.js");
} = doc;
/**
* Takes an abstract syntax tree (AST) and recursively converts it to a
@@ -119,7 +119,7 @@ function callPluginPrintFunction(path, options, printPath, args) {
if (node) {
try {
// Potentially switch to a different parser
doc = multiparser.printSubtree(path, printPath, options, printAstToDoc);
doc = printSubtree(path, printPath, options, printAstToDoc);
} catch (error) {
/* istanbul ignore if */
if (process.env.PRETTIER_DEBUG) {
@@ -148,4 +148,4 @@ function callPluginPrintFunction(path, options, printPath, args) {
return doc;
}
module.exports = printAstToDoc;
export default printAstToDoc;
+9 -9
View File
@@ -1,12 +1,8 @@
"use strict";
import assert from "assert";
const assert = require("assert");
import doc from "../document/index.js";
const {
builders: { line, hardline, breakParent, indent, lineSuffix, join, cursor },
} = require("../document/index.js");
const {
import {
hasNewline,
skipNewline,
skipSpaces,
@@ -14,7 +10,11 @@ const {
addLeadingComment,
addDanglingComment,
addTrailingComment,
} = require("../common/util.js");
} from "../common/util.js";
const {
builders: { line, hardline, breakParent, indent, lineSuffix, join, cursor },
} = doc;
const childNodesCache = new WeakMap();
function getSortedChildNodes(node, options, resultArray) {
@@ -601,7 +601,7 @@ function ensureAllCommentsPrinted(astComments) {
}
}
module.exports = {
export {
attach,
printComments,
printCommentsSeparately,
+2 -4
View File
@@ -1,6 +1,4 @@
"use strict";
const { outdent } = require("outdent");
import { outdent } from "outdent";
const CATEGORY_CONFIG = "Config";
const CATEGORY_EDITOR = "Editor";
@@ -266,7 +264,7 @@ const options = {
},
};
module.exports = {
export {
CATEGORY_CONFIG,
CATEGORY_EDITOR,
CATEGORY_FORMAT,
+28 -26
View File
@@ -1,25 +1,25 @@
"use strict";
// Use `diff/lib/diff/array.js` instead of `diff` to reduce bundle size
const { diffArrays } = require("diff/lib/diff/array.js");
import { diffArrays } from "diff/lib/diff/array.js";
const {
printer: { printDocToString },
debug: { printDocToDebug },
} = require("../document/index.js");
const { getAlignmentSize } = require("../common/util.js");
const {
import doc from "../document/index.js";
import { getAlignmentSize } from "../common/util.js";
import {
guessEndOfLine,
convertEndOfLineToChars,
countEndOfLineChars,
normalizeEndOfLine,
} = require("../common/end-of-line.js");
const normalizeOptions = require("./options.js").normalize;
const massageAST = require("./massage-ast.js");
const comments = require("./comments.js");
const parser = require("./parser.js");
const printAstToDoc = require("./ast-to-doc.js");
const rangeUtil = require("./range-util.js");
} from "../common/end-of-line.js";
import { normalize as normalizeOptions } from "./options.js";
import massageAST from "./massage-ast.js";
import { ensureAllCommentsPrinted, attach } from "./comments.js";
import { parse, resolveParser } from "./parser.js";
import printAstToDoc from "./ast-to-doc.js";
import { calculateRange, findNodeAtOffset } from "./range-util.js";
const {
printer: { printDocToString },
debug: { printDocToDebug },
} = doc;
const BOM = "\uFEFF";
@@ -29,7 +29,7 @@ function attachComments(text, ast, opts) {
const astComments = ast.comments;
if (astComments) {
delete ast.comments;
comments.attach(astComments, ast, text, opts);
attach(astComments, ast, text, opts);
}
opts[Symbol.for("comments")] = astComments || [];
opts[Symbol.for("tokens")] = ast.tokens || [];
@@ -42,10 +42,10 @@ function coreFormat(originalText, opts, addAlignmentSize = 0) {
return { formatted: "", cursorOffset: -1, comments: [] };
}
const { ast, text } = parser.parse(originalText, opts);
const { ast, text } = parse(originalText, opts);
if (opts.cursorOffset >= 0) {
const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
const nodeResult = findNodeAtOffset(ast, opts.cursorOffset, opts);
if (nodeResult && nodeResult.node) {
opts.cursorNode = nodeResult.node;
}
@@ -56,7 +56,7 @@ function coreFormat(originalText, opts, addAlignmentSize = 0) {
const result = printDocToString(doc, opts);
comments.ensureAllCommentsPrinted(astComments);
ensureAllCommentsPrinted(astComments);
// Remove extra leading indentation as well as the added indentation after last newline
if (addAlignmentSize > 0) {
const trimmed = result.formatted.trim();
@@ -146,8 +146,8 @@ function coreFormat(originalText, opts, addAlignmentSize = 0) {
}
function formatRange(originalText, opts) {
const { ast, text } = parser.parse(originalText, opts);
const { rangeStart, rangeEnd } = rangeUtil.calculateRange(text, opts, ast);
const { ast, text } = parse(originalText, opts);
const { rangeStart, rangeEnd } = calculateRange(text, opts, ast);
const rangeString = text.slice(rangeStart, rangeEnd);
// Try to extend the range backwards to the beginning of the line.
@@ -276,7 +276,7 @@ function normalizeInputAndOptions(text, options) {
}
function hasPragma(text, options) {
const selectedParser = parser.resolveParser(options);
const selectedParser = resolveParser(options);
return !selectedParser.hasPragma || selectedParser.hasPragma(text);
}
@@ -324,7 +324,7 @@ function formatWithCursor(originalText, originalOptions) {
return result;
}
module.exports = {
const prettier = {
formatWithCursor,
parse(originalText, originalOptions, massage) {
@@ -332,7 +332,7 @@ module.exports = {
originalText,
normalizeOptions(originalOptions)
);
const parsed = parser.parse(text, options);
const parsed = parse(text, options);
if (massage) {
parsed.ast = massageAST(parsed.ast, options);
}
@@ -355,7 +355,7 @@ module.exports = {
printToDoc(originalText, options) {
options = normalizeOptions(options);
const { ast, text } = parser.parse(originalText, options);
const { ast, text } = parse(originalText, options);
attachComments(text, ast, options);
return printAstToDoc(ast, options);
},
@@ -364,3 +364,5 @@ module.exports = {
return printDocToString(doc, normalizeOptions(options));
},
};
export default prettier;
+1 -3
View File
@@ -1,5 +1,3 @@
"use strict";
function massageAST(ast, options, parent) {
if (Array.isArray(ast)) {
return ast.map((e) => massageAST(e, options, parent)).filter(Boolean);
@@ -37,4 +35,4 @@ function massageAST(ast, options, parent) {
return newObj;
}
module.exports = massageAST;
export default massageAST;
+9 -10
View File
@@ -1,10 +1,11 @@
"use strict";
import doc from "../document/index.js";
import { normalize } from "./options.js";
import { ensureAllCommentsPrinted, attach } from "./comments.js";
import { parse } from "./parser.js";
const {
utils: { stripTrailingHardline },
} = require("../document/index.js");
const { normalize } = require("./options.js");
const comments = require("./comments.js");
} = doc;
function printSubtree(path, print, options, printAstToDoc) {
if (options.printer.embed && options.embeddedLanguageFormatting === "auto") {
@@ -42,18 +43,18 @@ function textToDoc(
{ passThrough: true }
);
const result = require("./parser.js").parse(text, nextOptions);
const result = parse(text, nextOptions);
const { ast } = result;
text = result.text;
const astComments = ast.comments;
delete ast.comments;
comments.attach(astComments, ast, text, nextOptions);
attach(astComments, ast, text, nextOptions);
nextOptions[Symbol.for("comments")] = astComments || [];
nextOptions[Symbol.for("tokens")] = ast.tokens || [];
const doc = printAstToDoc(ast, nextOptions);
comments.ensureAllCommentsPrinted(astComments);
ensureAllCommentsPrinted(astComments);
if (shouldStripTrailingHardline) {
// TODO: move this to `stripTrailingHardline` function in `/src/document/doc-utils.js`
@@ -68,6 +69,4 @@ function textToDoc(
return doc;
}
module.exports = {
printSubtree,
};
export { printSubtree };
+4 -9
View File
@@ -1,8 +1,6 @@
"use strict";
const vnopts = require("vnopts");
const leven = require("leven");
const getLast = require("../utils/get-last.js");
import vnopts from "vnopts";
import leven from "leven";
import getLast from "../utils/get-last.js";
const cliDescriptor = {
key: (key) => (key.length === 1 ? `-${key}` : `--${key}`),
@@ -257,7 +255,4 @@ function normalizeCliOptions(options, optionInfos, opts) {
return normalizeOptions(options, optionInfos, { isCLI: true, ...opts });
}
module.exports = {
normalizeApiOptions,
normalizeCliOptions,
};
export { normalizeApiOptions, normalizeCliOptions };
+10 -10
View File
@@ -1,10 +1,9 @@
"use strict";
const path = require("path");
const { UndefinedParserError } = require("../common/errors.js");
const { getSupportInfo } = require("../main/support.js");
const normalizer = require("./options-normalizer.js");
const { resolveParser } = require("./parser.js");
import { createRequire } from "module";
import path from "path";
import { UndefinedParserError } from "../common/errors.js";
import { getSupportInfo } from "../main/support.js";
import { normalizeApiOptions } from "./options-normalizer.js";
import { resolveParser } from "./parser.js";
const hiddenDefaults = {
astFormat: "estree",
@@ -52,7 +51,7 @@ function normalize(options, opts = {}) {
}
const parser = resolveParser(
normalizer.normalizeApiOptions(
normalizeApiOptions(
rawOptions,
[supportOptions.find((x) => x.name === "parser")],
{ passThrough: true, logger: false }
@@ -90,7 +89,7 @@ function normalize(options, opts = {}) {
rawOptions.trailingComma = "none";
}
return normalizer.normalizeApiOptions(rawOptions, supportOptions, {
return normalizeApiOptions(rawOptions, supportOptions, {
passThrough: Object.keys(hiddenDefaults),
...opts,
});
@@ -140,6 +139,7 @@ function inferParser(filepath, plugins) {
!language &&
!filename.includes(".")
) {
const require = createRequire(import.meta.url);
// `getInterpreter` requires file access, put `require()` in the `if` block,
// So we can easily remove this part during build
const getInterpreter = require("../utils/get-interpreter.js");
@@ -153,4 +153,4 @@ function inferParser(filepath, plugins) {
return language && language.parsers[0];
}
module.exports = { normalize, hiddenDefaults, inferParser };
export { normalize, hiddenDefaults, inferParser };
-5
View File
@@ -1,5 +0,0 @@
{
"//TODO": "Remove this file when we close #10157",
"type": "commonjs",
"description": "A package.json file to use `.js` files in this directory as CommonJS module."
}
+6 -8
View File
@@ -1,11 +1,9 @@
"use strict";
import { createRequire } from "module";
import path from "path";
import { ConfigError } from "../common/errors.js";
import { locStart, locEnd } from "../language-js/loc.js";
const path = require("path");
const { ConfigError } = require("../common/errors.js");
// TODO: Use esm version
const jsLoc = require("../language-js/loc.cjs");
const { locStart, locEnd } = jsLoc;
const require = createRequire(import.meta.url);
// Use defineProperties()/getOwnPropertyDescriptor() to prevent
// triggering the parsers getters.
@@ -111,4 +109,4 @@ function parse(text, opts) {
}
}
module.exports = { parse, resolveParser };
export { parse, resolveParser };
+4 -9
View File
@@ -1,7 +1,5 @@
"use strict";
const assert = require("assert");
const comments = require("./comments.js");
import assert from "assert";
import { getSortedChildNodes } from "./comments.js";
const isJsonParser = ({ parser }) =>
parser === "json" || parser === "json5" || parser === "json-stringify";
@@ -93,7 +91,7 @@ function findNodeAtOffset(
return;
}
for (const childNode of comments.getSortedChildNodes(node, options)) {
for (const childNode of getSortedChildNodes(node, options)) {
const childResult = findNodeAtOffset(
childNode,
offset,
@@ -252,7 +250,4 @@ function calculateRange(text, opts, ast) {
};
}
module.exports = {
calculateRange,
findNodeAtOffset,
};
export { calculateRange, findNodeAtOffset };
+12 -14
View File
@@ -1,13 +1,13 @@
"use strict";
import { createRequire } from "module";
import semverCompare from "semver/functions/compare.js";
import semverGte from "semver/functions/gte.js";
import semverLt from "semver/functions/lt.js";
import arrayify from "../utils/arrayify.js";
import { options as coreOptions } from "./core-options.js";
const require = createRequire(import.meta.url);
const semver = {
compare: require("semver/functions/compare"),
lt: require("semver/functions/lt"),
gte: require("semver/functions/gte"),
};
const arrayify = require("../utils/arrayify.js");
const currentVersion = require("../../package.json").version;
const coreOptions = require("./core-options.js").options;
/**
* Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version
@@ -50,7 +50,7 @@ function getSupportInfo({
: option.default
.filter(filterSince)
.sort((info1, info2) =>
semver.compare(info2.since, info1.since)
semverCompare(info2.since, info1.since)
)[0].value;
}
@@ -83,7 +83,7 @@ function getSupportInfo({
return (
showUnreleased ||
!("since" in object) ||
(object.since && semver.gte(version, object.since))
(object.since && semverGte(version, object.since))
);
}
@@ -91,7 +91,7 @@ function getSupportInfo({
return (
showDeprecated ||
!("deprecated" in object) ||
(object.deprecated && semver.lt(version, object.deprecated))
(object.deprecated && semverLt(version, object.deprecated))
);
}
@@ -125,6 +125,4 @@ function collectParsersFromLanguages(option, languages, plugins) {
}
}
module.exports = {
getSupportInfo,
};
export { getSupportInfo };
+1 -1
View File
@@ -1,7 +1,7 @@
import { createRequire } from "module";
import core from "./main/core.js";
import { getSupportInfo } from "./main/support.js";
import sharedUtil from "./common/util-shared.js";
import * as sharedUtil from "./common/util-shared.js";
import languages from "./languages.js";
import doc from "./document/index.js";
+1 -1
View File
@@ -2,7 +2,7 @@ import path from "node:path";
import createEsmUtils from "esm-utils";
import fastGlob from "fast-glob";
import { projectRoot } from "../env.js";
import coreOptions from "../../../src/main/core-options.js";
import * as coreOptions from "../../../src/main/core-options.js";
import codeSamples from "../../../website/playground/codeSamples.mjs";
import jestPathSerializer from "../path-serializer.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import sharedUtil from "../../../src/common/util-shared.js";
import * as sharedUtil from "../../../src/common/util-shared.js";
test("shared util has correct structure", () => {
expect(typeof sharedUtil.getMaxContinuousCount).toBe("function");