prettier
Version:
Prettier is an opinionated code formatter
1,668 lines (1,636 loc) • 140 kB
JavaScript
import { createRequire as __prettierCreateRequire } from "module";
import { fileURLToPath as __prettierFileUrlToPath } from "url";
import { dirname as __prettierDirname } from "path";
const require = __prettierCreateRequire(import.meta.url);
const __filename = __prettierFileUrlToPath(import.meta.url);
const __dirname = __prettierDirname(__filename);
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// node_modules/dashify/index.js
var require_dashify = __commonJS({
"node_modules/dashify/index.js"(exports, module) {
"use strict";
module.exports = (str, options) => {
if (typeof str !== "string") throw new TypeError("expected a string");
return str.trim().replace(/([a-z])([A-Z])/g, "$1-$2").replace(/\W/g, (m) => /[À-ž]/.test(m) ? m : "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, (m) => options && options.condense ? "-" : m).toLowerCase();
};
}
});
// node_modules/minimist/index.js
var require_minimist = __commonJS({
"node_modules/minimist/index.js"(exports, module) {
"use strict";
function hasKey(obj, keys2) {
var o = obj;
keys2.slice(0, -1).forEach(function(key2) {
o = o[key2] || {};
});
var key = keys2[keys2.length - 1];
return key in o;
}
function isNumber(x) {
if (typeof x === "number") {
return true;
}
if (/^0x[0-9a-f]+$/i.test(x)) {
return true;
}
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
function isConstructorOrProto(obj, key) {
return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
}
module.exports = function(args, opts) {
if (!opts) {
opts = {};
}
var flags = {
bools: {},
strings: {},
unknownFn: null
};
if (typeof opts.unknown === "function") {
flags.unknownFn = opts.unknown;
}
if (typeof opts.boolean === "boolean" && opts.boolean) {
flags.allBools = true;
} else {
[].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
flags.bools[key2] = true;
});
}
var aliases = {};
function aliasIsBoolean(key2) {
return aliases[key2].some(function(x) {
return flags.bools[x];
});
}
Object.keys(opts.alias || {}).forEach(function(key2) {
aliases[key2] = [].concat(opts.alias[key2]);
aliases[key2].forEach(function(x) {
aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function(key2) {
flags.strings[key2] = true;
if (aliases[key2]) {
[].concat(aliases[key2]).forEach(function(k) {
flags.strings[k] = true;
});
}
});
var defaults = opts.default || {};
var argv2 = { _: [] };
function argDefined(key2, arg2) {
return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
}
function setKey(obj, keys2, value2) {
var o = obj;
for (var i2 = 0; i2 < keys2.length - 1; i2++) {
var key2 = keys2[i2];
if (isConstructorOrProto(o, key2)) {
return;
}
if (o[key2] === void 0) {
o[key2] = {};
}
if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) {
o[key2] = {};
}
if (o[key2] === Array.prototype) {
o[key2] = [];
}
o = o[key2];
}
var lastKey = keys2[keys2.length - 1];
if (isConstructorOrProto(o, lastKey)) {
return;
}
if (o === Object.prototype || o === Number.prototype || o === String.prototype) {
o = {};
}
if (o === Array.prototype) {
o = [];
}
if (o[lastKey] === void 0 || flags.bools[lastKey] || typeof o[lastKey] === "boolean") {
o[lastKey] = value2;
} else if (Array.isArray(o[lastKey])) {
o[lastKey].push(value2);
} else {
o[lastKey] = [o[lastKey], value2];
}
}
function setArg(key2, val, arg2) {
if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
if (flags.unknownFn(arg2) === false) {
return;
}
}
var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val;
setKey(argv2, key2.split("."), value2);
(aliases[key2] || []).forEach(function(x) {
setKey(argv2, x.split("."), value2);
});
}
Object.keys(flags.bools).forEach(function(key2) {
setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
});
var notFlags = [];
if (args.indexOf("--") !== -1) {
notFlags = args.slice(args.indexOf("--") + 1);
args = args.slice(0, args.indexOf("--"));
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
var key;
var next;
if (/^--.+=/.test(arg)) {
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
key = m[1];
var value = m[2];
if (flags.bools[key]) {
value = value !== "false";
}
setArg(key, value, arg);
} else if (/^--no-.+/.test(arg)) {
key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
} else if (/^--.+/.test(arg)) {
key = arg.match(/^--(.+)/)[1];
next = args[i + 1];
if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i += 1;
} else if (/^(true|false)$/.test(next)) {
setArg(key, next === "true", arg);
i += 1;
} else {
setArg(key, flags.strings[key] ? "" : true, arg);
}
} else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1, -1).split("");
var broken = false;
for (var j = 0; j < letters.length; j++) {
next = arg.slice(j + 2);
if (next === "-") {
setArg(letters[j], next, arg);
continue;
}
if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") {
setArg(letters[j], next.slice(1), arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next, arg);
broken = true;
break;
}
if (letters[j + 1] && letters[j + 1].match(/\W/)) {
setArg(letters[j], arg.slice(j + 2), arg);
broken = true;
break;
} else {
setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
}
}
key = arg.slice(-1)[0];
if (!broken && key !== "-") {
if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i + 1], arg);
i += 1;
} else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
setArg(key, args[i + 1] === "true", arg);
i += 1;
} else {
setArg(key, flags.strings[key] ? "" : true, arg);
}
}
} else {
if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
argv2._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));
}
if (opts.stopEarly) {
argv2._.push.apply(argv2._, args.slice(i + 1));
break;
}
}
}
Object.keys(defaults).forEach(function(k) {
if (!hasKey(argv2, k.split("."))) {
setKey(argv2, k.split("."), defaults[k]);
(aliases[k] || []).forEach(function(x) {
setKey(argv2, x.split("."), defaults[k]);
});
}
});
if (opts["--"]) {
argv2["--"] = notFlags.slice();
} else {
notFlags.forEach(function(k) {
argv2._.push(k);
});
}
return argv2;
};
}
});
// node_modules/fast-json-stable-stringify/index.js
var require_fast_json_stable_stringify = __commonJS({
"node_modules/fast-json-stable-stringify/index.js"(exports, module) {
"use strict";
module.exports = function(data, opts) {
if (!opts) opts = {};
if (typeof opts === "function") opts = { cmp: opts };
var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false;
var cmp = opts.cmp && /* @__PURE__ */ function(f) {
return function(node) {
return function(a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
}(opts.cmp);
var seen = [];
return function stringify5(node) {
if (node && node.toJSON && typeof node.toJSON === "function") {
node = node.toJSON();
}
if (node === void 0) return;
if (typeof node == "number") return isFinite(node) ? "" + node : "null";
if (typeof node !== "object") return JSON.stringify(node);
var i, out;
if (Array.isArray(node)) {
out = "[";
for (i = 0; i < node.length; i++) {
if (i) out += ",";
out += stringify5(node[i]) || "null";
}
return out + "]";
}
if (node === null) return "null";
if (seen.indexOf(node) !== -1) {
if (cycles) return JSON.stringify("__cycle__");
throw new TypeError("Converting circular structure to JSON");
}
var seenIndex = seen.push(node) - 1;
var keys2 = Object.keys(node).sort(cmp && cmp(node));
out = "";
for (i = 0; i < keys2.length; i++) {
var key = keys2[i];
var value = stringify5(node[key]);
if (!value) continue;
if (out) out += ",";
out += JSON.stringify(key) + ":" + value;
}
seen.splice(seenIndex, 1);
return "{" + out + "}";
}(data);
};
}
});
// node_modules/common-path-prefix/index.js
var require_common_path_prefix = __commonJS({
"node_modules/common-path-prefix/index.js"(exports, module) {
"use strict";
var { sep: DEFAULT_SEPARATOR } = __require("path");
var determineSeparator = (paths) => {
for (const path13 of paths) {
const match = /(\/|\\)/.exec(path13);
if (match !== null) return match[0];
}
return DEFAULT_SEPARATOR;
};
module.exports = function commonPathPrefix2(paths, sep = determineSeparator(paths)) {
const [first = "", ...remaining] = paths;
if (first === "" || remaining.length === 0) return "";
const parts = first.split(sep);
let endOfPrefix = parts.length;
for (const path13 of remaining) {
const compare = path13.split(sep);
for (let i = 0; i < endOfPrefix; i++) {
if (compare[i] !== parts[i]) {
endOfPrefix = i;
}
}
if (endOfPrefix === 0) return "";
}
const prefix = parts.slice(0, endOfPrefix).join(sep);
return prefix.endsWith(sep) ? prefix : prefix + sep;
};
}
});
// node_modules/ci-info/vendors.json
var require_vendors = __commonJS({
"node_modules/ci-info/vendors.json"(exports, module) {
module.exports = [
{
name: "Agola CI",
constant: "AGOLA",
env: "AGOLA_GIT_REF",
pr: "AGOLA_PULL_REQUEST_ID"
},
{
name: "Appcircle",
constant: "APPCIRCLE",
env: "AC_APPCIRCLE",
pr: {
env: "AC_GIT_PR",
ne: "false"
}
},
{
name: "AppVeyor",
constant: "APPVEYOR",
env: "APPVEYOR",
pr: "APPVEYOR_PULL_REQUEST_NUMBER"
},
{
name: "AWS CodeBuild",
constant: "CODEBUILD",
env: "CODEBUILD_BUILD_ARN",
pr: {
env: "CODEBUILD_WEBHOOK_EVENT",
any: [
"PULL_REQUEST_CREATED",
"PULL_REQUEST_UPDATED",
"PULL_REQUEST_REOPENED"
]
}
},
{
name: "Azure Pipelines",
constant: "AZURE_PIPELINES",
env: "TF_BUILD",
pr: {
BUILD_REASON: "PullRequest"
}
},
{
name: "Bamboo",
constant: "BAMBOO",
env: "bamboo_planKey"
},
{
name: "Bitbucket Pipelines",
constant: "BITBUCKET",
env: "BITBUCKET_COMMIT",
pr: "BITBUCKET_PR_ID"
},
{
name: "Bitrise",
constant: "BITRISE",
env: "BITRISE_IO",
pr: "BITRISE_PULL_REQUEST"
},
{
name: "Buddy",
constant: "BUDDY",
env: "BUDDY_WORKSPACE_ID",
pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
},
{
name: "Buildkite",
constant: "BUILDKITE",
env: "BUILDKITE",
pr: {
env: "BUILDKITE_PULL_REQUEST",
ne: "false"
}
},
{
name: "CircleCI",
constant: "CIRCLE",
env: "CIRCLECI",
pr: "CIRCLE_PULL_REQUEST"
},
{
name: "Cirrus CI",
constant: "CIRRUS",
env: "CIRRUS_CI",
pr: "CIRRUS_PR"
},
{
name: "Cloudflare Pages",
constant: "CLOUDFLARE_PAGES",
env: "CF_PAGES"
},
{
name: "Codefresh",
constant: "CODEFRESH",
env: "CF_BUILD_ID",
pr: {
any: [
"CF_PULL_REQUEST_NUMBER",
"CF_PULL_REQUEST_ID"
]
}
},
{
name: "Codemagic",
constant: "CODEMAGIC",
env: "CM_BUILD_ID",
pr: "CM_PULL_REQUEST"
},
{
name: "Codeship",
constant: "CODESHIP",
env: {
CI_NAME: "codeship"
}
},
{
name: "Drone",
constant: "DRONE",
env: "DRONE",
pr: {
DRONE_BUILD_EVENT: "pull_request"
}
},
{
name: "dsari",
constant: "DSARI",
env: "DSARI"
},
{
name: "Earthly",
constant: "EARTHLY",
env: "EARTHLY_CI"
},
{
name: "Expo Application Services",
constant: "EAS",
env: "EAS_BUILD"
},
{
name: "Gerrit",
constant: "GERRIT",
env: "GERRIT_PROJECT"
},
{
name: "Gitea Actions",
constant: "GITEA_ACTIONS",
env: "GITEA_ACTIONS"
},
{
name: "GitHub Actions",
constant: "GITHUB_ACTIONS",
env: "GITHUB_ACTIONS",
pr: {
GITHUB_EVENT_NAME: "pull_request"
}
},
{
name: "GitLab CI",
constant: "GITLAB",
env: "GITLAB_CI",
pr: "CI_MERGE_REQUEST_ID"
},
{
name: "GoCD",
constant: "GOCD",
env: "GO_PIPELINE_LABEL"
},
{
name: "Google Cloud Build",
constant: "GOOGLE_CLOUD_BUILD",
env: "BUILDER_OUTPUT"
},
{
name: "Harness CI",
constant: "HARNESS",
env: "HARNESS_BUILD_ID"
},
{
name: "Heroku",
constant: "HEROKU",
env: {
env: "NODE",
includes: "/app/.heroku/node/bin/node"
}
},
{
name: "Hudson",
constant: "HUDSON",
env: "HUDSON_URL"
},
{
name: "Jenkins",
constant: "JENKINS",
env: [
"JENKINS_URL",
"BUILD_ID"
],
pr: {
any: [
"ghprbPullId",
"CHANGE_ID"
]
}
},
{
name: "LayerCI",
constant: "LAYERCI",
env: "LAYERCI",
pr: "LAYERCI_PULL_REQUEST"
},
{
name: "Magnum CI",
constant: "MAGNUM",
env: "MAGNUM"
},
{
name: "Netlify CI",
constant: "NETLIFY",
env: "NETLIFY",
pr: {
env: "PULL_REQUEST",
ne: "false"
}
},
{
name: "Nevercode",
constant: "NEVERCODE",
env: "NEVERCODE",
pr: {
env: "NEVERCODE_PULL_REQUEST",
ne: "false"
}
},
{
name: "Prow",
constant: "PROW",
env: "PROW_JOB_ID"
},
{
name: "ReleaseHub",
constant: "RELEASEHUB",
env: "RELEASE_BUILD_ID"
},
{
name: "Render",
constant: "RENDER",
env: "RENDER",
pr: {
IS_PULL_REQUEST: "true"
}
},
{
name: "Sail CI",
constant: "SAIL",
env: "SAILCI",
pr: "SAIL_PULL_REQUEST_NUMBER"
},
{
name: "Screwdriver",
constant: "SCREWDRIVER",
env: "SCREWDRIVER",
pr: {
env: "SD_PULL_REQUEST",
ne: "false"
}
},
{
name: "Semaphore",
constant: "SEMAPHORE",
env: "SEMAPHORE",
pr: "PULL_REQUEST_NUMBER"
},
{
name: "Sourcehut",
constant: "SOURCEHUT",
env: {
CI_NAME: "sourcehut"
}
},
{
name: "Strider CD",
constant: "STRIDER",
env: "STRIDER"
},
{
name: "TaskCluster",
constant: "TASKCLUSTER",
env: [
"TASK_ID",
"RUN_ID"
]
},
{
name: "TeamCity",
constant: "TEAMCITY",
env: "TEAMCITY_VERSION"
},
{
name: "Travis CI",
constant: "TRAVIS",
env: "TRAVIS",
pr: {
env: "TRAVIS_PULL_REQUEST",
ne: "false"
}
},
{
name: "Vela",
constant: "VELA",
env: "VELA",
pr: {
VELA_PULL_REQUEST: "1"
}
},
{
name: "Vercel",
constant: "VERCEL",
env: {
any: [
"NOW_BUILDER",
"VERCEL"
]
},
pr: "VERCEL_GIT_PULL_REQUEST_ID"
},
{
name: "Visual Studio App Center",
constant: "APPCENTER",
env: "APPCENTER_BUILD_ID"
},
{
name: "Woodpecker",
constant: "WOODPECKER",
env: {
CI: "woodpecker"
},
pr: {
CI_BUILD_EVENT: "pull_request"
}
},
{
name: "Xcode Cloud",
constant: "XCODE_CLOUD",
env: "CI_XCODE_PROJECT",
pr: "CI_PULL_REQUEST_NUMBER"
},
{
name: "Xcode Server",
constant: "XCODE_SERVER",
env: "XCS"
}
];
}
});
// node_modules/ci-info/index.js
var require_ci_info = __commonJS({
"node_modules/ci-info/index.js"(exports) {
"use strict";
var vendors = require_vendors();
var env3 = process.env;
Object.defineProperty(exports, "_vendors", {
value: vendors.map(function(v) {
return v.constant;
})
});
exports.name = null;
exports.isPR = null;
exports.id = null;
vendors.forEach(function(vendor) {
const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
const isCI2 = envs.every(function(obj) {
return checkEnv(obj);
});
exports[vendor.constant] = isCI2;
if (!isCI2) {
return;
}
exports.name = vendor.name;
exports.isPR = checkPR(vendor);
exports.id = vendor.constant;
});
exports.isCI = !!(env3.CI !== "false" && // Bypass all checks if CI env is explicitly set to 'false'
(env3.BUILD_ID || // Jenkins, Cloudbees
env3.BUILD_NUMBER || // Jenkins, TeamCity
env3.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari, Cloudflare Pages
env3.CI_APP_ID || // Appflow
env3.CI_BUILD_ID || // Appflow
env3.CI_BUILD_NUMBER || // Appflow
env3.CI_NAME || // Codeship and others
env3.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
env3.RUN_ID || // TaskCluster, dsari
exports.name || false));
function checkEnv(obj) {
if (typeof obj === "string") return !!env3[obj];
if ("env" in obj) {
return env3[obj.env] && env3[obj.env].includes(obj.includes);
}
if ("any" in obj) {
return obj.any.some(function(k) {
return !!env3[k];
});
}
return Object.keys(obj).every(function(k) {
return env3[k] === obj[k];
});
}
function checkPR(vendor) {
switch (typeof vendor.pr) {
case "string":
return !!env3[vendor.pr];
case "object":
if ("env" in vendor.pr) {
if ("any" in vendor.pr) {
return vendor.pr.any.some(function(key) {
return env3[vendor.pr.env] === key;
});
} else {
return vendor.pr.env in env3 && env3[vendor.pr.env] !== vendor.pr.ne;
}
} else if ("any" in vendor.pr) {
return vendor.pr.any.some(function(key) {
return !!env3[key];
});
} else {
return checkEnv(vendor.pr);
}
default:
return null;
}
}
}
});
// src/cli/index.js
import * as prettier2 from "../index.mjs";
// scripts/build/shims/at.js
var at = (isOptionalObject, object2, index) => {
if (isOptionalObject && (object2 === void 0 || object2 === null)) {
return;
}
if (Array.isArray(object2) || typeof object2 === "string") {
return object2[index < 0 ? object2.length + index : index];
}
return object2.at(index);
};
var at_default = at;
// src/cli/options/get-context-options.js
var import_dashify = __toESM(require_dashify(), 1);
import { getSupportInfo } from "../index.mjs";
// src/cli/cli-options.evaluate.js
var cli_options_evaluate_default = {
"cache": {
"default": false,
"description": "Only format changed files. Cannot use with --stdin-filepath.",
"type": "boolean"
},
"cacheLocation": {
"description": "Path to the cache file.",
"type": "path"
},
"cacheStrategy": {
"choices": [
{
"description": "Use the file metadata such as timestamps as cache keys",
"value": "metadata"
},
{
"description": "Use the file content as cache keys",
"value": "content"
}
],
"description": "Strategy for the cache to use for detecting changed files.",
"type": "choice"
},
"check": {
"alias": "c",
"category": "Output",
"description": "Check if the given files are formatted, print a human-friendly summary\nmessage and paths to unformatted files (see also --list-different).",
"type": "boolean"
},
"color": {
"default": true,
"description": "Colorize error messages.",
"oppositeDescription": "Do not colorize error messages.",
"type": "boolean"
},
"config": {
"category": "Config",
"description": "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
"exception": (value) => value === false,
"oppositeDescription": "Do not look for a configuration file.",
"type": "path"
},
"configPrecedence": {
"category": "Config",
"choices": [
{
"description": "CLI options take precedence over config file",
"value": "cli-override"
},
{
"description": "Config file take precedence over CLI options",
"value": "file-override"
},
{
"description": "If a config file is found will evaluate it and ignore other CLI options.\nIf no config file is found CLI options will evaluate as normal.",
"value": "prefer-file"
}
],
"default": "cli-override",
"description": "Define in which order config files and CLI options should be evaluated.",
"type": "choice"
},
"debugBenchmark": {
"type": "boolean"
},
"debugCheck": {
"type": "boolean"
},
"debugPrintAst": {
"type": "boolean"
},
"debugPrintComments": {
"type": "boolean"
},
"debugPrintDoc": {
"type": "boolean"
},
"debugRepeat": {
"default": 0,
"type": "int"
},
"editorconfig": {
"category": "Config",
"default": true,
"description": "Take .editorconfig into account when parsing configuration.",
"oppositeDescription": "Don't take .editorconfig into account when parsing configuration.",
"type": "boolean"
},
"errorOnUnmatchedPattern": {
"oppositeDescription": "Prevent errors when pattern is unmatched.",
"type": "boolean"
},
"fileInfo": {
"description": "Extract the following info (as JSON) for a given file path. Reported fields:\n* ignored (boolean) - true if file path is filtered by --ignore-path\n* inferredParser (string | null) - name of parser inferred from file path",
"type": "path"
},
"findConfigPath": {
"category": "Config",
"description": "Find and print the path to a configuration file for the given input file.",
"type": "path"
},
"help": {
"alias": "h",
"description": "Show CLI usage, or details about the given flag.\nExample: --help write",
"exception": (value) => value === "",
"type": "flag"
},
"ignorePath": {
"array": true,
"category": "Config",
"default": [
{
"value": [
".gitignore",
".prettierignore"
]
}
],
"description": "Path to a file with patterns describing files to ignore.\nMultiple values are accepted.",
"type": "path"
},
"ignoreUnknown": {
"alias": "u",
"description": "Ignore unknown files.",
"type": "boolean"
},
"listDifferent": {
"alias": "l",
"category": "Output",
"description": "Print the names of files that are different from Prettier's formatting (see also --check).",
"type": "boolean"
},
"logLevel": {
"choices": [
"silent",
"error",
"warn",
"log",
"debug"
],
"default": "log",
"description": "What level of logs to report.",
"type": "choice"
},
"supportInfo": {
"description": "Print support information as JSON.",
"type": "boolean"
},
"version": {
"alias": "v",
"description": "Print Prettier version.",
"type": "boolean"
},
"withNodeModules": {
"category": "Config",
"description": "Process files inside 'node_modules' directory.",
"type": "boolean"
},
"write": {
"alias": "w",
"category": "Output",
"description": "Edit files in-place. (Beware!)",
"type": "boolean"
}
};
// src/cli/prettier-internal.js
import { __internal as sharedWithCli } from "../index.mjs";
var {
errors,
optionCategories,
createIsIgnoredFunction,
formatOptionsHiddenDefaults,
normalizeOptions,
getSupportInfoWithoutPlugins,
normalizeOptionSettings,
vnopts,
fastGlob,
createTwoFilesPatch,
picocolors,
leven
} = sharedWithCli;
// src/cli/options/get-context-options.js
var detailedCliOptions = normalizeOptionSettings(cli_options_evaluate_default).map(
(option) => normalizeDetailedOption(option)
);
function apiOptionToCliOption(apiOption) {
const cliOption = {
...apiOption,
description: apiOption.cliDescription ?? apiOption.description,
category: apiOption.cliCategory ?? optionCategories.CATEGORY_FORMAT,
forwardToApi: apiOption.name
};
if (apiOption.deprecated) {
delete cliOption.forwardToApi;
delete cliOption.description;
delete cliOption.oppositeDescription;
cliOption.deprecated = true;
}
return normalizeDetailedOption(cliOption);
}
function normalizeDetailedOption(option) {
var _a;
return {
category: optionCategories.CATEGORY_OTHER,
...option,
name: option.cliName ?? (0, import_dashify.default)(option.name),
choices: (_a = option.choices) == null ? void 0 : _a.map((choice) => {
const newChoice = {
description: "",
deprecated: false,
...typeof choice === "object" ? choice : { value: choice }
};
if (newChoice.value === true) {
newChoice.value = "";
}
return newChoice;
})
};
}
function supportInfoToContextOptions({ options: supportOptions, languages }) {
const detailedOptions = [
...detailedCliOptions,
...supportOptions.map((apiOption) => apiOptionToCliOption(apiOption))
];
return {
supportOptions,
languages,
detailedOptions
};
}
async function getContextOptions(plugins) {
const supportInfo = await getSupportInfo({
showDeprecated: true,
plugins
});
return supportInfoToContextOptions(supportInfo);
}
function getContextOptionsWithoutPlugins() {
const supportInfo = getSupportInfoWithoutPlugins();
return supportInfoToContextOptions(supportInfo);
}
// scripts/build/shims/string-replace-all.js
var stringReplaceAll = (isOptionalObject, original, pattern, replacement) => {
if (isOptionalObject && (original === void 0 || original === null)) {
return;
}
if (original.replaceAll) {
return original.replaceAll(pattern, replacement);
}
if (pattern.global) {
return original.replace(pattern, replacement);
}
return original.split(pattern).join(replacement);
};
var string_replace_all_default = stringReplaceAll;
// node_modules/camelcase/index.js
var UPPERCASE = /[\p{Lu}]/u;
var LOWERCASE = /[\p{Ll}]/u;
var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
var SEPARATORS = /[_.\- ]+/;
var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
var preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
let isLastLastCharPreserved = false;
for (let index = 0; index < string.length; index++) {
const character = string[index];
isLastLastCharPreserved = index > 2 ? string[index - 3] === "-" : true;
if (isLastCharLower && UPPERCASE.test(character)) {
string = string.slice(0, index) + "-" + string.slice(index);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
index++;
} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
string = string.slice(0, index - 1) + "-" + string.slice(index - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
}
}
return string;
};
var preserveConsecutiveUppercase = (input, toLowerCase) => {
LEADING_CAPITAL.lastIndex = 0;
return string_replace_all_default(
/* isOptionalObject */
false,
input,
LEADING_CAPITAL,
(match) => toLowerCase(match)
);
};
var postProcess = (input, toUpperCase) => {
SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
NUMBERS_AND_IDENTIFIER.lastIndex = 0;
return string_replace_all_default(
/* isOptionalObject */
false,
string_replace_all_default(
/* isOptionalObject */
false,
input,
NUMBERS_AND_IDENTIFIER,
(match, pattern, offset) => ["_", "-"].includes(input.charAt(offset + match.length)) ? match : toUpperCase(match)
),
SEPARATORS_AND_IDENTIFIER,
(_2, identifier) => toUpperCase(identifier)
);
};
function camelCase(input, options) {
if (!(typeof input === "string" || Array.isArray(input))) {
throw new TypeError("Expected the input to be `string | string[]`");
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
if (input.length === 1) {
if (SEPARATORS.test(input)) {
return "";
}
return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
}
const hasUpperCase = input !== toLowerCase(input);
if (hasUpperCase) {
input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
}
input = input.replace(LEADING_SEPARATORS, "");
input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
if (options.pascalCase) {
input = toUpperCase(input.charAt(0)) + input.slice(1);
}
return postProcess(input, toUpperCase);
}
// src/cli/utils.js
import fs from "fs/promises";
import path from "path";
// node_modules/sdbm/index.js
function sdbm(string) {
let hash2 = 0;
for (let i = 0; i < string.length; i++) {
hash2 = string.charCodeAt(i) + (hash2 << 6) + (hash2 << 16) - hash2;
}
return hash2 >>> 0;
}
// src/cli/utils.js
import { __internal as sharedWithCli2 } from "../index.mjs";
var printToScreen = console.log.bind(console);
function groupBy(array, iteratee) {
const result = /* @__PURE__ */ Object.create(null);
for (const value of array) {
const key = iteratee(value);
if (Array.isArray(result[key])) {
result[key].push(value);
} else {
result[key] = [value];
}
}
return result;
}
function pick(object2, keys2) {
const entries = keys2.map((key) => [key, object2[key]]);
return Object.fromEntries(entries);
}
function createHash(source) {
return String(sdbm(source));
}
async function statSafe(filePath) {
try {
return await fs.stat(filePath);
} catch (error) {
if (error.code !== "ENOENT") {
throw error;
}
}
}
async function lstatSafe(filePath) {
try {
return await fs.lstat(filePath);
} catch (error) {
if (error.code !== "ENOENT") {
throw error;
}
}
}
function isJson(value) {
try {
JSON.parse(value);
return true;
} catch {
return false;
}
}
var normalizeToPosix = path.sep === "\\" ? (filepath) => string_replace_all_default(
/* isOptionalObject */
false,
filepath,
"\\",
"/"
) : (filepath) => filepath;
var { omit } = sharedWithCli2.utils;
// src/cli/options/create-minimist-options.js
function createMinimistOptions(detailedOptions) {
const booleanNames = [];
const stringNames = [];
const defaultValues = {};
for (const option of detailedOptions) {
const { name, alias, type } = option;
const names = type === "boolean" ? booleanNames : stringNames;
names.push(name);
if (alias) {
names.push(alias);
}
if (!option.deprecated && (!option.forwardToApi || name === "plugin") && option.default !== void 0) {
defaultValues[option.name] = option.default;
}
}
return {
// we use vnopts' AliasSchema to handle aliases for better error messages
alias: {},
boolean: booleanNames,
string: stringNames,
default: defaultValues
};
}
// src/cli/options/minimist.js
var import_minimist = __toESM(require_minimist(), 1);
var PLACEHOLDER = null;
function minimistParse(args, options) {
const boolean = options.boolean ?? [];
const defaults = options.default ?? {};
const booleanWithoutDefault = boolean.filter((key) => !(key in defaults));
const newDefaults = {
...defaults,
...Object.fromEntries(
booleanWithoutDefault.map((key) => [key, PLACEHOLDER])
)
};
const parsed = (0, import_minimist.default)(args, { ...options, default: newDefaults });
return Object.fromEntries(
Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER)
);
}
// src/cli/options/normalize-cli-options.js
var descriptor = {
key: (key) => key.length === 1 ? `-${key}` : `--${key}`,
value: (value) => vnopts.apiDescriptor.value(value),
pair: ({ key, value }) => value === false ? `--no-${key}` : value === true ? descriptor.key(key) : value === "" ? `${descriptor.key(key)} without an argument` : `${descriptor.key(key)}=${value}`
};
var _flags;
var FlagSchema = class extends vnopts.ChoiceSchema {
constructor({ name, flags }) {
super({ name, choices: flags });
__privateAdd(this, _flags, []);
__privateSet(this, _flags, [...flags].sort());
}
preprocess(value, utils) {
if (typeof value === "string" && value.length > 0 && !__privateGet(this, _flags).includes(value)) {
const suggestion = __privateGet(this, _flags).find((flag) => leven(flag, value) < 3);
if (suggestion) {
utils.logger.warn(
[
`Unknown flag ${picocolors.yellow(utils.descriptor.value(value))},`,
`did you mean ${picocolors.blue(utils.descriptor.value(suggestion))}?`
].join(" ")
);
return suggestion;
}
}
return value;
}
expected() {
return "a flag";
}
};
_flags = new WeakMap();
function normalizeCliOptions(options, optionInfos, opts) {
return normalizeOptions(options, optionInfos, {
...opts,
isCLI: true,
FlagSchema,
descriptor
});
}
var normalize_cli_options_default = normalizeCliOptions;
// src/cli/options/parse-cli-arguments.js
function parseArgv(rawArguments, detailedOptions, logger, keys2) {
var _a;
const minimistOptions = createMinimistOptions(detailedOptions);
let argv2 = minimistParse(rawArguments, minimistOptions);
if (keys2) {
detailedOptions = detailedOptions.filter(
(option) => keys2.includes(option.name)
);
argv2 = pick(argv2, keys2);
}
const normalized = normalize_cli_options_default(argv2, detailedOptions, { logger });
return {
...Object.fromEntries(
Object.entries(normalized).map(([key, value]) => {
const option = detailedOptions.find(({ name }) => name === key) || {};
return [option.forwardToApi || camelCase(key), value];
})
),
_: (_a = normalized._) == null ? void 0 : _a.map(String),
get __raw() {
return argv2;
}
};
}
var { detailedOptions: detailedOptionsWithoutPlugins } = getContextOptionsWithoutPlugins();
function parseArgvWithoutPlugins(rawArguments, logger, keys2) {
return parseArgv(
rawArguments,
detailedOptionsWithoutPlugins,
logger,
typeof keys2 === "string" ? [keys2] : keys2
);
}
// src/cli/context.js
var _stack;
var Context = class {
constructor({ rawArguments, logger }) {
__privateAdd(this, _stack, []);
this.rawArguments = rawArguments;
this.logger = logger;
}
async init() {
const { rawArguments, logger } = this;
const { plugins } = parseArgvWithoutPlugins(rawArguments, logger, [
"plugin"
]);
await this.pushContextPlugins(plugins);
const argv2 = parseArgv(rawArguments, this.detailedOptions, logger);
this.argv = argv2;
this.filePatterns = argv2._;
}
/**
* @param {string[]} plugins
*/
async pushContextPlugins(plugins) {
const options = await getContextOptions(plugins);
__privateGet(this, _stack).push(options);
Object.assign(this, options);
}
popContextPlugins() {
__privateGet(this, _stack).pop();
Object.assign(this, at_default(
/* isOptionalObject */
false,
__privateGet(this, _stack),
-1
));
}
// eslint-disable-next-line getter-return
get performanceTestFlag() {
const { debugBenchmark, debugRepeat } = this.argv;
if (debugBenchmark) {
return {
name: "--debug-benchmark",
debugBenchmark: true
};
}
if (debugRepeat > 0) {
return {
name: "--debug-repeat",
debugRepeat
};
}
const { PRETTIER_PERF_REPEAT } = process.env;
if (PRETTIER_PERF_REPEAT && /^\d+$/u.test(PRETTIER_PERF_REPEAT)) {
return {
name: "PRETTIER_PERF_REPEAT (environment variable)",
debugRepeat: Number(PRETTIER_PERF_REPEAT)
};
}
}
};
_stack = new WeakMap();
var context_default = Context;
// src/cli/file-info.js
var import_fast_json_stable_stringify = __toESM(require_fast_json_stable_stringify(), 1);
import path2 from "path";
import { format, getFileInfo } from "../index.mjs";
async function logFileInfoOrDie(context) {
const {
fileInfo: file,
ignorePath,
withNodeModules: withNodeModules2,
plugins,
config
} = context.argv;
const fileInfo = await getFileInfo(path2.resolve(file), {
ignorePath,
withNodeModules: withNodeModules2,
plugins: plugins.length > 0 ? plugins : void 0,
resolveConfig: config !== false
});
const result = await format((0, import_fast_json_stable_stringify.default)(fileInfo), { parser: "json" });
printToScreen(result.trim());
}
var file_info_default = logFileInfoOrDie;
// src/cli/find-config-path.js
import path3 from "path";
import { resolveConfigFile } from "../index.mjs";
async function logResolvedConfigPathOrDie(context) {
const file = context.argv.findConfigPath;
const configFile = await resolveConfigFile(file);
if (configFile) {
printToScreen(normalizeToPosix(path3.relative(process.cwd(), configFile)));
} else {
throw new Error(`Can not find configure file for "${file}".`);
}
}
var find_config_path_default = logResolvedConfigPathOrDie;
// src/cli/format.js
import fs9 from "fs/promises";
import path12 from "path";
// node_modules/get-stdin/index.js
var { stdin } = process;
async function getStdin() {
let result = "";
if (stdin.isTTY) {
return result;
}
stdin.setEncoding("utf8");
for await (const chunk of stdin) {
result += chunk;
}
return result;
}
getStdin.buffer = async () => {
const result = [];
let length = 0;
if (stdin.isTTY) {
return Buffer.concat([]);
}
for await (const chunk of stdin) {
result.push(chunk);
length += chunk.length;
}
return Buffer.concat(result, length);
};
// src/cli/format.js
import * as prettier from "../index.mjs";
// src/cli/expand-patterns.js
import path5 from "path";
// src/cli/directory-ignorer.js
import path4 from "path";
var alwaysIgnoredDirectories = [".git", ".sl", ".svn", ".hg", ".jj"];
var withNodeModules = [...alwaysIgnoredDirectories, "node_modules"];
var cwd = process.cwd();
var _directories;
var DirectoryIgnorer = class {
constructor(shouldIgnoreNodeModules) {
__privateAdd(this, _directories);
__publicField(this, "ignorePatterns");
const directories = shouldIgnoreNodeModules ? withNodeModules : alwaysIgnoredDirectories;
const patterns = directories.map((directory) => `**/${directory}`);
__privateSet(this, _directories, new Set(directories));
this.ignorePatterns = patterns;
}
/**
* @param {string} absolutePathOrPattern
*/
shouldIgnore(absolutePathOrPattern) {
const directoryNames = path4.relative(cwd, absolutePathOrPattern).split(path4.sep);
return directoryNames.some(
(directoryName) => __privateGet(this, _directories).has(directoryName)
);
}
};
_directories = new WeakMap();
var directoryIgnorerWithNodeModules = new DirectoryIgnorer(
/* shouldIgnoreNodeModules */
true
);
var directoryIgnorerWithoutNodeModules = new DirectoryIgnorer(
/* shouldIgnoreNodeModules */
false
);
// src/cli/expand-patterns.js
async function* expandPatterns(context) {
const seen = /* @__PURE__ */ new Set();
let noResults = true;
for await (const { filePath, ignoreUnknown, error } of expandPatternsInternal(
context
)) {
noResults = false;
if (error) {
yield { error };
continue;
}
const filename = path5.resolve(filePath);
if (seen.has(filename)) {
continue;
}
seen.add(filename);
yield { filename, ignoreUnknown };
}
if (noResults && context.argv.errorOnUnmatchedPattern !== false) {
yield {
error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
};
}
}
async function* expandPatternsInternal(context) {
const directoryIgnorer = context.argv.withNodeModules === true ? directoryIgnorerWithoutNodeModules : directoryIgnorerWithNodeModules;
const globOptions = {
dot: true,
ignore: [...directoryIgnorer.ignorePatterns],
followSymbolicLinks: false
};
const cwd3 = process.cwd();
const entries = [];
for (const pattern of context.filePatterns) {
const absolutePath = path5.resolve(pattern);
if (directoryIgnorer.shouldIgnore(absolutePath)) {
continue;
}
const stat = await lstatSafe(absolutePath);
if (stat) {
if (stat.isSymbolicLink()) {
if (context.argv.errorOnUnmatchedPattern !== false) {
yield {
error: `Explicitly specified pattern "${pattern}" is a symbolic link.`
};
} else {
context.logger.debug(
`Skipping pattern "${pattern}", as it is a symbolic link.`
);
}
} else if (stat.isFile()) {
entries.push({
type: "file",
glob: escapePathForGlob(fixWindowsSlashes(pattern)),
input: pattern
});
} else if (stat.isDirectory()) {
const relativePath = path5.relative(cwd3, absolutePath) || ".";
const prefix = escapePathForGlob(fixWindowsSlashes(relativePath));
entries.push({
type: "dir",
glob: `${prefix}/**/*`,
input: pattern,
ignoreUnknown: true
});
}
} else if (pattern[0] === "!") {
globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
} else {
entries.push({
type: "glob",
glob: fixWindowsSlashes(pattern),
input: pattern
});
}
}
for (const { type, glob, input, ignoreUnknown } of entries) {
let result;
try {
result = await fastGlob(glob, globOptions);
} catch ({ message }) {
yield {
error: `${errorMessages.globError[type]}: "${input}".
${message}`
};
continue;
}
if (result.length === 0) {
if (context.argv.errorOnUnmatchedPattern !== false) {
yield { error: `${errorMessages.emptyResults[type]}: "${input}".` };
}
} else {
yield* sortPaths(result).map((filePath) => ({ filePath, ignoreUnknown }));
}
}
}
var errorMessages = {
globError: {
file: "Unable to resolve file",
dir: "Unable to expand directory",
glob: "Unable to expand glob pattern"
},
emptyResults: {
file: "Explicitly specified file was ignored due to negative glob patterns",
dir: "No supported files were found in the directory",
glob: "No files matching the pattern were found"
}
};
function sortPaths(paths) {
return paths.sort((a, b) => a.localeCompare(b));
}
function escapePathForGlob(path13) {
return string_replace_all_default(
/* isOptionalObject */
false,
string_replace_all_default(