UNPKG

prettier

Version:

Prettier is an opinionated code formatter

1,422 lines (1,405 loc) 125 kB
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 __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 __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); // 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, keys) { var o = obj; keys.slice(0, -1).forEach(function(key2) { o = o[key2] || {}; }); var key = keys[keys.length - 1]; return key in o; } function isNumber(x) { if (typeof x === "number") { return true; } if (/^0x[0-9a-f]+$/i.test(x)) { return true; } return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } 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 argv = { _: [] }; function argDefined(key2, arg2) { return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2]; } function setKey(obj, keys, value2) { var o = obj; for (var i2 = 0; i2 < keys.length - 1; i2++) { var key2 = keys[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 = keys[keys.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(argv, key2.split("."), value2); (aliases[key2] || []).forEach(function(x) { setKey(argv, 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) { argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i + 1)); break; } } } Object.keys(defaults).forEach(function(k) { if (!hasKey(argv, k.split("."))) { setKey(argv, k.split("."), defaults[k]); (aliases[k] || []).forEach(function(x) { setKey(argv, x.split("."), defaults[k]); }); } }); if (opts["--"]) { argv["--"] = notFlags.slice(); } else { notFlags.forEach(function(k) { argv._.push(k); }); } return argv; }; } }); // 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 stringify4(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 += stringify4(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 keys = Object.keys(node).sort(cmp && cmp(node)); out = ""; for (i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify4(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 path10 of paths) { const match = /(\/|\\)/.exec(path10); 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 path10 of remaining) { const compare = path10.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/json-buffer/index.js var require_json_buffer = __commonJS({ "node_modules/json-buffer/index.js"(exports) { exports.stringify = function stringify4(o) { if ("undefined" == typeof o) return o; if (o && Buffer.isBuffer(o)) return JSON.stringify(":base64:" + o.toString("base64")); if (o && o.toJSON) o = o.toJSON(); if (o && "object" === typeof o) { var s = ""; var array2 = Array.isArray(o); s = array2 ? "[" : "{"; var first = true; for (var k in o) { var ignore = "function" == typeof o[k] || !array2 && "undefined" === typeof o[k]; if (Object.hasOwnProperty.call(o, k) && !ignore) { if (!first) s += ","; first = false; if (array2) { if (o[k] == void 0) s += "null"; else s += stringify4(o[k]); } else if (o[k] !== void 0) { s += stringify4(k) + ":" + stringify4(o[k]); } } } s += array2 ? "]" : "}"; return s; } else if ("string" === typeof o) { return JSON.stringify(/^:/.test(o) ? ":" + o : o); } else if ("undefined" === typeof o) { return "null"; } else return JSON.stringify(o); }; exports.parse = function(s) { return JSON.parse(s, function(key, value) { if ("string" === typeof value) { if (/^:base64:/.test(value)) return Buffer.from(value.substring(8), "base64"); else return /^:/.test(value) ? value.substring(1) : value; } return value; }); }; } }); // node_modules/keyv/src/index.js var require_src = __commonJS({ "node_modules/keyv/src/index.js"(exports, module) { "use strict"; var EventEmitter = __require("events"); var JSONB = require_json_buffer(); var loadStore = (options) => { const adapters = { redis: "@keyv/redis", rediss: "@keyv/redis", mongodb: "@keyv/mongo", mongo: "@keyv/mongo", sqlite: "@keyv/sqlite", postgresql: "@keyv/postgres", postgres: "@keyv/postgres", mysql: "@keyv/mysql", etcd: "@keyv/etcd", offline: "@keyv/offline", tiered: "@keyv/tiered" }; if (options.adapter || options.uri) { const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; return new (__require(adapters[adapter]))(options); } return /* @__PURE__ */ new Map(); }; var iterableAdapters = [ "sqlite", "postgres", "mysql", "mongo", "redis", "tiered" ]; var Keyv = class extends EventEmitter { constructor(uri, { emitErrors = true, ...options } = {}) { super(); this.opts = { namespace: "keyv", serialize: JSONB.stringify, deserialize: JSONB.parse, ...typeof uri === "string" ? { uri } : uri, ...options }; if (!this.opts.store) { const adapterOptions = { ...this.opts }; this.opts.store = loadStore(adapterOptions); } if (this.opts.compression) { const compression = this.opts.compression; this.opts.serialize = compression.serialize.bind(compression); this.opts.deserialize = compression.deserialize.bind(compression); } if (typeof this.opts.store.on === "function" && emitErrors) { this.opts.store.on("error", (error) => this.emit("error", error)); } this.opts.store.namespace = this.opts.namespace; const generateIterator = (iterator) => async function* () { for await (const [key, raw] of typeof iterator === "function" ? iterator(this.opts.store.namespace) : iterator) { const data = await this.opts.deserialize(raw); if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { continue; } if (typeof data.expires === "number" && Date.now() > data.expires) { this.delete(key); continue; } yield [this._getKeyUnprefix(key), data.value]; } }; if (typeof this.opts.store[Symbol.iterator] === "function" && this.opts.store instanceof Map) { this.iterator = generateIterator(this.opts.store); } else if (typeof this.opts.store.iterator === "function" && this.opts.store.opts && this._checkIterableAdaptar()) { this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); } } _checkIterableAdaptar() { return iterableAdapters.includes(this.opts.store.opts.dialect) || iterableAdapters.findIndex((element) => this.opts.store.opts.url.includes(element)) >= 0; } _getKeyPrefix(key) { return `${this.opts.namespace}:${key}`; } _getKeyPrefixArray(keys) { return keys.map((key) => `${this.opts.namespace}:${key}`); } _getKeyUnprefix(key) { return key.split(":").splice(1).join(":"); } get(key, options) { const { store } = this.opts; const isArray = Array.isArray(key); const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); if (isArray && store.getMany === void 0) { const promises = []; for (const key2 of keyPrefixed) { promises.push( Promise.resolve().then(() => store.get(key2)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => { if (data === void 0 || data === null) { return void 0; } if (typeof data.expires === "number" && Date.now() > data.expires) { return this.delete(key2).then(() => void 0); } return options && options.raw ? data : data.value; }) ); } return Promise.allSettled(promises).then((values) => { const data = []; for (const value of values) { data.push(value.value); } return data; }); } return Promise.resolve().then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => { if (data === void 0 || data === null) { return void 0; } if (isArray) { return data.map((row, index) => { if (typeof row === "string") { row = this.opts.deserialize(row); } if (row === void 0 || row === null) { return void 0; } if (typeof row.expires === "number" && Date.now() > row.expires) { this.delete(key[index]).then(() => void 0); return void 0; } return options && options.raw ? row : row.value; }); } if (typeof data.expires === "number" && Date.now() > data.expires) { return this.delete(key).then(() => void 0); } return options && options.raw ? data : data.value; }); } set(key, value, ttl) { const keyPrefixed = this._getKeyPrefix(key); if (typeof ttl === "undefined") { ttl = this.opts.ttl; } if (ttl === 0) { ttl = void 0; } const { store } = this.opts; return Promise.resolve().then(() => { const expires = typeof ttl === "number" ? Date.now() + ttl : null; if (typeof value === "symbol") { this.emit("error", "symbol cannot be serialized"); } value = { value, expires }; return this.opts.serialize(value); }).then((value2) => store.set(keyPrefixed, value2, ttl)).then(() => true); } delete(key) { const { store } = this.opts; if (Array.isArray(key)) { const keyPrefixed2 = this._getKeyPrefixArray(key); if (store.deleteMany === void 0) { const promises = []; for (const key2 of keyPrefixed2) { promises.push(store.delete(key2)); } return Promise.allSettled(promises).then((values) => values.every((x) => x.value === true)); } return Promise.resolve().then(() => store.deleteMany(keyPrefixed2)); } const keyPrefixed = this._getKeyPrefix(key); return Promise.resolve().then(() => store.delete(keyPrefixed)); } clear() { const { store } = this.opts; return Promise.resolve().then(() => store.clear()); } has(key) { const keyPrefixed = this._getKeyPrefix(key); const { store } = this.opts; return Promise.resolve().then(async () => { if (typeof store.has === "function") { return store.has(keyPrefixed); } const value = await store.get(keyPrefixed); return value !== void 0; }); } disconnect() { const { store } = this.opts; if (typeof store.disconnect === "function") { return store.disconnect(); } } }; module.exports = Keyv; } }); // node_modules/flatted/cjs/index.js var require_cjs = __commonJS({ "node_modules/flatted/cjs/index.js"(exports) { "use strict"; var { parse: $parse, stringify: $stringify } = JSON; var { keys } = Object; var Primitive = String; var primitive = "string"; var ignore = {}; var object = "object"; var noop = (_2, value) => value; var primitives = (value) => value instanceof Primitive ? Primitive(value) : value; var Primitives = (_2, value) => typeof value === primitive ? new Primitive(value) : value; var revive = (input, parsed, output, $) => { const lazy = []; for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) { const k = ke[y]; const value = output[k]; if (value instanceof Primitive) { const tmp = input[value]; if (typeof tmp === object && !parsed.has(tmp)) { parsed.add(tmp); output[k] = ignore; lazy.push({ k, a: [input, parsed, tmp, $] }); } else output[k] = $.call(output, k, tmp); } else if (output[k] !== ignore) output[k] = $.call(output, k, value); } for (let { length } = lazy, i = 0; i < length; i++) { const { k, a } = lazy[i]; output[k] = $.call(output, k, revive.apply(null, a)); } return output; }; var set = (known, input, value) => { const index = Primitive(input.push(value) - 1); known.set(value, index); return index; }; var parse = (text, reviver) => { const input = $parse(text, Primitives).map(primitives); const value = input[0]; const $ = reviver || noop; const tmp = typeof value === object && value ? revive(input, /* @__PURE__ */ new Set(), value, $) : value; return $.call({ "": tmp }, "", tmp); }; exports.parse = parse; var stringify4 = (value, replacer, space) => { const $ = replacer && typeof replacer === object ? (k, v) => k === "" || -1 < replacer.indexOf(k) ? v : void 0 : replacer || noop; const known = /* @__PURE__ */ new Map(); const input = []; const output = []; let i = +set(known, input, $.call({ "": value }, "", value)); let firstRun = !i; while (i < input.length) { firstRun = true; output[i] = $stringify(input[i++], replace, space); } return "[" + output.join(",") + "]"; function replace(key, value2) { if (firstRun) { firstRun = !firstRun; return value2; } const after = $.call(this, key, value2); switch (typeof after) { case object: if (after === null) return after; case primitive: return known.get(after) || set(known, input, after); } return after; } }; exports.stringify = stringify4; var toJSON = (value) => $parse(stringify4(value)); exports.toJSON = toJSON; var fromJSON = (value) => parse($stringify(value)); exports.fromJSON = fromJSON; } }); // node_modules/flat-cache/src/utils.js var require_utils = __commonJS({ "node_modules/flat-cache/src/utils.js"(exports, module) { var fs6 = __require("fs"); var path10 = __require("path"); var flatted = require_cjs(); function tryParse(filePath, defaultValue) { let result; try { result = readJSON(filePath); } catch { result = defaultValue; } return result; } function readJSON(filePath) { return flatted.parse( fs6.readFileSync(filePath, { encoding: "utf8" }) ); } function writeJSON(filePath, data) { fs6.mkdirSync(path10.dirname(filePath), { recursive: true }); fs6.writeFileSync(filePath, flatted.stringify(data)); } module.exports = { tryParse, readJSON, writeJSON }; } }); // node_modules/flat-cache/src/del.js var require_del = __commonJS({ "node_modules/flat-cache/src/del.js"(exports, module) { var fs6 = __require("fs"); var path10 = __require("path"); function del(targetPath) { if (!fs6.existsSync(targetPath)) { return false; } try { if (fs6.statSync(targetPath).isDirectory()) { for (const file of fs6.readdirSync(targetPath)) { const currentPath = path10.join(targetPath, file); if (fs6.statSync(currentPath).isFile()) { fs6.unlinkSync(currentPath); } } fs6.rmdirSync(targetPath); } else { fs6.unlinkSync(targetPath); } return true; } catch (error) { console.error(`Error while deleting ${targetPath}: ${error.message}`); } } module.exports = { del }; } }); // node_modules/flat-cache/src/cache.js var require_cache = __commonJS({ "node_modules/flat-cache/src/cache.js"(exports, module) { var path10 = __require("path"); var fs6 = __require("fs"); var Keyv = require_src(); var { writeJSON, tryParse } = require_utils(); var { del } = require_del(); var cache = { /** * Load a cache identified by the given Id. If the element does not exists, then initialize an empty * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted * then the cache module directory `./cache` will be used instead * * @method load * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry */ load(documentId, cacheDir) { const me = this; me.keyv = new Keyv(); me.__visited = {}; me.__persisted = {}; me._pathToFile = cacheDir ? path10.resolve(cacheDir, documentId) : path10.resolve(__dirname, "../.cache/", documentId); if (fs6.existsSync(me._pathToFile)) { me._persisted = tryParse(me._pathToFile, {}); } }, get _persisted() { return this.__persisted; }, set _persisted(value) { this.__persisted = value; }, get _visited() { return this.__visited; }, set _visited(value) { this.__visited = value; }, /** * Load the cache from the provided file * @method loadFile * @param {String} pathToFile the path to the file containing the info for the cache */ loadFile(pathToFile) { const me = this; const dir = path10.dirname(pathToFile); const fName = path10.basename(pathToFile); me.load(fName, dir); }, /** * Returns the entire persisted object * @method all * @returns {*} */ all() { return this._persisted; }, keys() { return Object.keys(this._persisted); }, /** * Sets a key to a given value * @method setKey * @param key {string} the key to set * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify */ setKey(key, value) { this._visited[key] = true; this._persisted[key] = value; }, /** * Remove a given key from the cache * @method removeKey * @param key {String} the key to remove from the object */ removeKey(key) { delete this._visited[key]; delete this._persisted[key]; }, /** * Return the value of the provided key * @method getKey * @param key {String} the name of the key to retrieve * @returns {*} the value from the key */ getKey(key) { this._visited[key] = true; return this._persisted[key]; }, /** * Remove keys that were not accessed/set since the * last time the `prune` method was called. * @method _prune * @private */ _prune() { const me = this; const object = {}; const keys = Object.keys(me._visited); if (keys.length === 0) { return; } for (const key of keys) { object[key] = me._persisted[key]; } me._visited = {}; me._persisted = object; }, /** * Save the state of the cache identified by the docId to disk * as a JSON structure * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files * @method save */ save(noPrune) { const me = this; !noPrune && me._prune(); writeJSON(me._pathToFile, me._persisted); }, /** * Remove the file where the cache is persisted * @method removeCacheFile * @return {Boolean} true or false if the file was successfully deleted */ removeCacheFile() { return del(this._pathToFile); }, /** * Destroy the file cache and cache content. * @method destroy */ destroy() { const me = this; me._visited = {}; me._persisted = {}; me.removeCacheFile(); } }; module.exports = { /** * Alias for create. Should be considered depreacted. Will be removed in next releases * * @method load * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry * @returns {cache} cache instance */ load(documentId, cacheDir) { return this.create(documentId, cacheDir); }, /** * Load a cache identified by the given Id. If the element does not exists, then initialize an empty * cache storage. * * @method create * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry * @returns {cache} cache instance */ create(documentId, cacheDir) { const object = Object.create(cache); object.load(documentId, cacheDir); return object; }, createFromFile(filePath) { const object = Object.create(cache); object.loadFile(filePath); return object; }, /** * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly * * @method clearCache * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param cacheDir {String} the directory where the cache file was written * @returns {Boolean} true if the cache folder was deleted. False otherwise */ clearCacheById(documentId, cacheDir) { const filePath = cacheDir ? path10.resolve(cacheDir, documentId) : path10.resolve(__dirname, "../.cache/", documentId); return del(filePath); }, /** * Remove all cache stored in the cache directory * @method clearAll * @returns {Boolean} true if the cache folder was deleted. False otherwise */ clearAll(cacheDir) { const filePath = cacheDir ? path10.resolve(cacheDir) : path10.resolve(__dirname, "../.cache/"); return del(filePath); } }; } }); // node_modules/file-entry-cache/cache.js var require_cache2 = __commonJS({ "node_modules/file-entry-cache/cache.js"(exports, module) { var path10 = __require("path"); var crypto = __require("crypto"); module.exports = { createFromFile(filePath, useChecksum, currentWorkingDir) { const fname = path10.basename(filePath); const dir = path10.dirname(filePath); return this.create(fname, dir, useChecksum, currentWorkingDir); }, create(cacheId, _path, useChecksum, currentWorkingDir) { const fs6 = __require("fs"); const flatCache = require_cache(); const cache = flatCache.load(cacheId, _path); let normalizedEntries = {}; const removeNotFoundFiles = function removeNotFoundFiles2() { const cachedEntries = cache.keys(); for (const fPath of cachedEntries) { try { let filePath = fPath; if (currentWorkingDir) { filePath = path10.join(currentWorkingDir, fPath); } fs6.statSync(filePath); } catch (error) { if (error.code === "ENOENT") { cache.removeKey(fPath); } } } }; removeNotFoundFiles(); return { /** * The flat cache storage used to persist the metadata of the `files * @type {Object} */ cache, /** * To enable relative paths as the key with current working directory * @type {string} */ currentWorkingDir: currentWorkingDir ?? void 0, /** * Given a buffer, calculate md5 hash of its content. * @method getHash * @param {Buffer} buffer buffer to calculate hash on * @return {String} content hash digest */ getHash(buffer) { return crypto.createHash("md5").update(buffer).digest("hex"); }, /** * Return whether or not a file has changed since last time reconcile was called. * @method hasFileChanged * @param {String} file the filepath to check * @return {Boolean} wheter or not the file has changed */ hasFileChanged(file) { return this.getFileDescriptor(file).changed; }, /** * Given an array of file paths it return and object with three arrays: * - changedFiles: Files that changed since previous run * - notChangedFiles: Files that haven't change * - notFoundFiles: Files that were not found, probably deleted * * @param {Array} files the files to analyze and compare to the previous seen files * @return {[type]} [description] */ analyzeFiles(files) { const me = this; files || (files = []); const res = { changedFiles: [], notFoundFiles: [], notChangedFiles: [] }; for (const entry of me.normalizeEntries(files)) { if (entry.changed) { res.changedFiles.push(entry.key); continue; } if (entry.notFound) { res.notFoundFiles.push(entry.key); continue; } res.notChangedFiles.push(entry.key); } return res; }, getFileDescriptor(file) { let fstat; try { fstat = fs6.statSync(file); } catch (error) { this.removeEntry(file); return { key: file, notFound: true, err: error }; } if (useChecksum) { return this._getFileDescriptorUsingChecksum(file); } return this._getFileDescriptorUsingMtimeAndSize(file, fstat); }, _getFileKey(file) { if (this.currentWorkingDir) { return file.split(this.currentWorkingDir).pop(); } return file; }, _getFileDescriptorUsingMtimeAndSize(file, fstat) { let meta = cache.getKey(this._getFileKey(file)); const cacheExists = Boolean(meta); const cSize = fstat.size; const cTime = fstat.mtime.getTime(); let isDifferentDate; let isDifferentSize; if (meta) { isDifferentDate = cTime !== meta.mtime; isDifferentSize = cSize !== meta.size; } else { meta = { size: cSize, mtime: cTime }; } const nEntry = normalizedEntries[this._getFileKey(file)] = { key: this._getFileKey(file), changed: !cacheExists || isDifferentDate || isDifferentSize, meta }; return nEntry; }, _getFileDescriptorUsingChecksum(file) { let meta = cache.getKey(this._getFileKey(file)); const cacheExists = Boolean(meta); let contentBuffer; try { contentBuffer = fs6.readFileSync(file); } catch { contentBuffer = ""; } let isDifferent = true; const hash = this.getHash(contentBuffer); if (meta) { isDifferent = hash !== meta.hash; } else { meta = { hash }; } const nEntry = normalizedEntries[this._getFileKey(file)] = { key: this._getFileKey(file), changed: !cacheExists || isDifferent, meta }; return nEntry; }, /** * Return the list o the files that changed compared * against the ones stored in the cache * * @method getUpdated * @param files {Array} the array of files to compare against the ones in the cache * @returns {Array} */ getUpdatedFiles(files) { const me = this; files || (files = []); return me.normalizeEntries(files).filter((entry) => entry.changed).map((entry) => entry.key); }, /** * Return the list of files * @method normalizeEntries * @param files * @returns {*} */ normalizeEntries(files) { files || (files = []); const me = this; const nEntries = files.map((file) => me.getFileDescriptor(file)); return nEntries; }, /** * Remove an entry from the file-entry-cache. Useful to force the file to still be considered * modified the next time the process is run * * @method removeEntry * @param entryName */ removeEntry(entryName) { delete normalizedEntries[this._getFileKey(entryName)]; cache.removeKey(this._getFileKey(entryName)); }, /** * Delete the cache file from the disk * @method deleteCacheFile */ deleteCacheFile() { cache.removeCacheFile(); }, /** * Remove the cache from the file and clear the memory cache */ destroy() { normalizedEntries = {}; cache.destroy(); }, _getMetaForFileUsingCheckSum(cacheEntry) { let filePath = cacheEntry.key; if (this.currentWorkingDir) { filePath = path10.join(this.currentWorkingDir, filePath); } const contentBuffer = fs6.readFileSync(filePath); const hash = this.getHash(contentBuffer); const meta = Object.assign(cacheEntry.meta, { hash }); delete meta.size; delete meta.mtime; return meta; }, _getMetaForFileUsingMtimeAndSize(cacheEntry) { let filePath = cacheEntry.key; if (currentWorkingDir) { filePath = path10.join(currentWorkingDir, filePath); } const stat = fs6.statSync(filePath); const meta = Object.assign(cacheEntry.meta, { size: stat.size, mtime: stat.mtime.getTime() }); delete meta.hash; return meta; }, /** * Sync the files and persist them to the cache * @method reconcile */ reconcile(noPrune) { removeNotFoundFiles(); noPrune = noPrune === void 0 ? true : noPrune; const entries = normalizedEntries; const keys = Object.keys(entries); if (keys.length === 0) { return; } const me = this; for (const entryName of keys) { const cacheEntry = entries[entryName]; try { const meta = useChecksum ? me._getMetaForFileUsingCheckSum(cacheEntry) : me._getMetaForFileUsingMtimeAndSize(cacheEntry); cache.setKey(this._getFileKey(entryName), meta); } catch (error) { if (error.code !== "ENOENT") { throw error; } } } cache.save(noPrune); } }; } }; } }); // src/cli/index.js import * as prettier2 from "../index.mjs"; // scripts/build/shims/at.js var at = (isOptionalObject, object, index) => { if (isOptionalObject && (object === void 0 || object === null)) { return; } if (Array.isArray(object) || typeof object === "string") { return object[index < 0 ? object.length + index : index]; } return object.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, createTwoFile