logger.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { o as __toESM, t as __commonJSMin } from "./chunk.js";
  2. import { readFileSync } from "node:fs";
  3. import path, { resolve } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import readline from "node:readline";
  6. //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
  7. var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8. let p = process || {}, argv = p.argv || [], env = p.env || {};
  9. let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
  10. let formatter = (open, close, replace = open) => (input) => {
  11. let string = "" + input, index = string.indexOf(close, open.length);
  12. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
  13. };
  14. let replaceClose = (string, close, replace, index) => {
  15. let result = "", cursor = 0;
  16. do {
  17. result += string.substring(cursor, index) + replace;
  18. cursor = index + close.length;
  19. index = string.indexOf(close, cursor);
  20. } while (~index);
  21. return result + string.substring(cursor);
  22. };
  23. let createColors = (enabled = isColorSupported) => {
  24. let f = enabled ? formatter : () => String;
  25. return {
  26. isColorSupported: enabled,
  27. reset: f("\x1B[0m", "\x1B[0m"),
  28. bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
  29. dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
  30. italic: f("\x1B[3m", "\x1B[23m"),
  31. underline: f("\x1B[4m", "\x1B[24m"),
  32. inverse: f("\x1B[7m", "\x1B[27m"),
  33. hidden: f("\x1B[8m", "\x1B[28m"),
  34. strikethrough: f("\x1B[9m", "\x1B[29m"),
  35. black: f("\x1B[30m", "\x1B[39m"),
  36. red: f("\x1B[31m", "\x1B[39m"),
  37. green: f("\x1B[32m", "\x1B[39m"),
  38. yellow: f("\x1B[33m", "\x1B[39m"),
  39. blue: f("\x1B[34m", "\x1B[39m"),
  40. magenta: f("\x1B[35m", "\x1B[39m"),
  41. cyan: f("\x1B[36m", "\x1B[39m"),
  42. white: f("\x1B[37m", "\x1B[39m"),
  43. gray: f("\x1B[90m", "\x1B[39m"),
  44. bgBlack: f("\x1B[40m", "\x1B[49m"),
  45. bgRed: f("\x1B[41m", "\x1B[49m"),
  46. bgGreen: f("\x1B[42m", "\x1B[49m"),
  47. bgYellow: f("\x1B[43m", "\x1B[49m"),
  48. bgBlue: f("\x1B[44m", "\x1B[49m"),
  49. bgMagenta: f("\x1B[45m", "\x1B[49m"),
  50. bgCyan: f("\x1B[46m", "\x1B[49m"),
  51. bgWhite: f("\x1B[47m", "\x1B[49m"),
  52. blackBright: f("\x1B[90m", "\x1B[39m"),
  53. redBright: f("\x1B[91m", "\x1B[39m"),
  54. greenBright: f("\x1B[92m", "\x1B[39m"),
  55. yellowBright: f("\x1B[93m", "\x1B[39m"),
  56. blueBright: f("\x1B[94m", "\x1B[39m"),
  57. magentaBright: f("\x1B[95m", "\x1B[39m"),
  58. cyanBright: f("\x1B[96m", "\x1B[39m"),
  59. whiteBright: f("\x1B[97m", "\x1B[39m"),
  60. bgBlackBright: f("\x1B[100m", "\x1B[49m"),
  61. bgRedBright: f("\x1B[101m", "\x1B[49m"),
  62. bgGreenBright: f("\x1B[102m", "\x1B[49m"),
  63. bgYellowBright: f("\x1B[103m", "\x1B[49m"),
  64. bgBlueBright: f("\x1B[104m", "\x1B[49m"),
  65. bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
  66. bgCyanBright: f("\x1B[106m", "\x1B[49m"),
  67. bgWhiteBright: f("\x1B[107m", "\x1B[49m")
  68. };
  69. };
  70. module.exports = createColors();
  71. module.exports.createColors = createColors;
  72. }));
  73. //#endregion
  74. //#region src/node/constants.ts
  75. const { version } = JSON.parse(readFileSync(new URL("../../package.json", new URL("../../../src/node/constants.ts", import.meta.url))).toString());
  76. const ROLLUP_HOOKS = [
  77. "options",
  78. "buildStart",
  79. "buildEnd",
  80. "renderStart",
  81. "renderError",
  82. "renderChunk",
  83. "writeBundle",
  84. "generateBundle",
  85. "banner",
  86. "footer",
  87. "augmentChunkHash",
  88. "outputOptions",
  89. "intro",
  90. "outro",
  91. "closeBundle",
  92. "closeWatcher",
  93. "load",
  94. "moduleParsed",
  95. "watchChange",
  96. "resolveDynamicImport",
  97. "resolveId",
  98. "transform",
  99. "onLog"
  100. ];
  101. const VERSION = version;
  102. const DEFAULT_MAIN_FIELDS = [
  103. "browser",
  104. "module",
  105. "jsnext:main",
  106. "jsnext"
  107. ];
  108. const DEFAULT_CLIENT_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS);
  109. const DEFAULT_SERVER_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser"));
  110. /**
  111. * A special condition that would be replaced with production or development
  112. * depending on NODE_ENV env variable
  113. */
  114. const DEV_PROD_CONDITION = `development|production`;
  115. const DEFAULT_CONDITIONS = [
  116. "module",
  117. "browser",
  118. "node",
  119. DEV_PROD_CONDITION
  120. ];
  121. const DEFAULT_CLIENT_CONDITIONS = Object.freeze(DEFAULT_CONDITIONS.filter((c) => c !== "node"));
  122. const DEFAULT_SERVER_CONDITIONS = Object.freeze(DEFAULT_CONDITIONS.filter((c) => c !== "browser"));
  123. const DEFAULT_EXTERNAL_CONDITIONS = Object.freeze(["node", "module-sync"]);
  124. const DEFAULT_EXTENSIONS = [
  125. ".mjs",
  126. ".js",
  127. ".mts",
  128. ".ts",
  129. ".jsx",
  130. ".tsx",
  131. ".json"
  132. ];
  133. /**
  134. * The browser versions that are included in the Baseline Widely Available on 2025-05-01.
  135. *
  136. * This value would be bumped on each major release of Vite.
  137. *
  138. * The value is generated by `pnpm generate-target` script.
  139. */
  140. const ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET = [
  141. "chrome111",
  142. "edge111",
  143. "firefox114",
  144. "safari16.4",
  145. "ios16.4"
  146. ];
  147. const DEFAULT_CONFIG_FILES = [
  148. "vite.config.js",
  149. "vite.config.mjs",
  150. "vite.config.ts",
  151. "vite.config.cjs",
  152. "vite.config.mts",
  153. "vite.config.cts"
  154. ];
  155. const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
  156. const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
  157. const OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
  158. const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
  159. /**
  160. * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
  161. */
  162. const FS_PREFIX = `/@fs/`;
  163. const CLIENT_PUBLIC_PATH = `/@vite/client`;
  164. const ENV_PUBLIC_PATH = `/@vite/env`;
  165. const VITE_PACKAGE_DIR = resolve(fileURLToPath(new URL("../../../src/node/constants.ts", import.meta.url)), "../../..");
  166. const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
  167. const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
  168. const CLIENT_DIR = path.dirname(CLIENT_ENTRY);
  169. const KNOWN_ASSET_TYPES = [
  170. "apng",
  171. "bmp",
  172. "png",
  173. "jpe?g",
  174. "jfif",
  175. "pjpeg",
  176. "pjp",
  177. "gif",
  178. "svg",
  179. "ico",
  180. "webp",
  181. "avif",
  182. "cur",
  183. "jxl",
  184. "mp4",
  185. "webm",
  186. "ogg",
  187. "mp3",
  188. "wav",
  189. "flac",
  190. "aac",
  191. "opus",
  192. "mov",
  193. "m4a",
  194. "vtt",
  195. "woff2?",
  196. "eot",
  197. "ttf",
  198. "otf",
  199. "webmanifest",
  200. "pdf",
  201. "txt"
  202. ];
  203. const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`, "i");
  204. const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
  205. const loopbackHosts = new Set([
  206. "localhost",
  207. "127.0.0.1",
  208. "::1",
  209. "0000:0000:0000:0000:0000:0000:0000:0001"
  210. ]);
  211. const wildcardHosts = new Set([
  212. "0.0.0.0",
  213. "::",
  214. "0000:0000:0000:0000:0000:0000:0000:0000"
  215. ]);
  216. const DEFAULT_DEV_PORT = 5173;
  217. const DEFAULT_PREVIEW_PORT = 4173;
  218. const DEFAULT_ASSETS_INLINE_LIMIT = 4096;
  219. const defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
  220. const METADATA_FILENAME = "_metadata.json";
  221. const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR";
  222. const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR";
  223. //#endregion
  224. //#region src/node/logger.ts
  225. var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
  226. const LogLevels = {
  227. silent: 0,
  228. error: 1,
  229. warn: 2,
  230. info: 3
  231. };
  232. let lastType;
  233. let lastMsg;
  234. let sameCount = 0;
  235. function clearScreen() {
  236. const repeatCount = process.stdout.rows - 2;
  237. const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
  238. console.log(blank);
  239. readline.cursorTo(process.stdout, 0, 0);
  240. readline.clearScreenDown(process.stdout);
  241. }
  242. let timeFormatter;
  243. function getTimeFormatter() {
  244. timeFormatter ??= new Intl.DateTimeFormat(void 0, {
  245. hour: "numeric",
  246. minute: "numeric",
  247. second: "numeric"
  248. });
  249. return timeFormatter;
  250. }
  251. function createLogger(level = "info", options = {}) {
  252. if (options.customLogger) return options.customLogger;
  253. const loggedErrors = /* @__PURE__ */ new WeakSet();
  254. const { prefix = "[vite]", allowClearScreen = true, console = globalThis.console } = options;
  255. const thresh = LogLevels[level];
  256. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  257. const clear = canClearScreen ? clearScreen : () => {};
  258. function format(type, msg, options = {}) {
  259. if (options.timestamp) {
  260. let tag = "";
  261. if (type === "info") tag = import_picocolors.default.cyan(import_picocolors.default.bold(prefix));
  262. else if (type === "warn") tag = import_picocolors.default.yellow(import_picocolors.default.bold(prefix));
  263. else tag = import_picocolors.default.red(import_picocolors.default.bold(prefix));
  264. const environment = options.environment ? options.environment + " " : "";
  265. return `${import_picocolors.default.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${environment}${msg}`;
  266. } else return msg;
  267. }
  268. function output(type, msg, options = {}) {
  269. if (thresh >= LogLevels[type]) {
  270. const method = type === "info" ? "log" : type;
  271. if (options.error) loggedErrors.add(options.error);
  272. if (canClearScreen) if (type === lastType && msg === lastMsg) {
  273. sameCount++;
  274. clear();
  275. console[method](format(type, msg, options), import_picocolors.default.yellow(`(x${sameCount + 1})`));
  276. } else {
  277. sameCount = 0;
  278. lastMsg = msg;
  279. lastType = type;
  280. if (options.clear) clear();
  281. console[method](format(type, msg, options));
  282. }
  283. else console[method](format(type, msg, options));
  284. }
  285. }
  286. const warnedMessages = /* @__PURE__ */ new Set();
  287. const logger = {
  288. hasWarned: false,
  289. info(msg, opts) {
  290. output("info", msg, opts);
  291. },
  292. warn(msg, opts) {
  293. logger.hasWarned = true;
  294. output("warn", msg, opts);
  295. },
  296. warnOnce(msg, opts) {
  297. if (warnedMessages.has(msg)) return;
  298. logger.hasWarned = true;
  299. output("warn", msg, opts);
  300. warnedMessages.add(msg);
  301. },
  302. error(msg, opts) {
  303. logger.hasWarned = true;
  304. output("error", msg, opts);
  305. },
  306. clearScreen(type) {
  307. if (thresh >= LogLevels[type]) clear();
  308. },
  309. hasErrorLogged(error) {
  310. return loggedErrors.has(error);
  311. }
  312. };
  313. return logger;
  314. }
  315. function printServerUrls(urls, optionsHost, info) {
  316. const colorUrl = (url) => import_picocolors.default.cyan(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
  317. for (const url of urls.local) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Local")}: ${colorUrl(url)}`);
  318. for (const url of urls.network) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: ${colorUrl(url)}`);
  319. if (urls.network.length === 0 && optionsHost === void 0) info(import_picocolors.default.dim(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: use `) + import_picocolors.default.bold("--host") + import_picocolors.default.dim(" to expose"));
  320. }
  321. //#endregion
  322. export { OPTIMIZABLE_ENTRY_RE as A, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR as C, JS_TYPES_RE as D, FS_PREFIX as E, defaultAllowedOrigins as F, loopbackHosts as I, wildcardHosts as L, SPECIAL_QUERY_RE as M, VERSION as N, KNOWN_ASSET_TYPES as O, VITE_PACKAGE_DIR as P, require_picocolors as R, ENV_PUBLIC_PATH as S, ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET as T, DEFAULT_SERVER_CONDITIONS as _, CLIENT_ENTRY as a, DEV_PROD_CONDITION as b, DEFAULT_ASSETS_INLINE_LIMIT as c, DEFAULT_CLIENT_MAIN_FIELDS as d, DEFAULT_CONFIG_FILES as f, DEFAULT_PREVIEW_PORT as g, DEFAULT_EXTERNAL_CONDITIONS as h, CLIENT_DIR as i, ROLLUP_HOOKS as j, METADATA_FILENAME as k, DEFAULT_ASSETS_RE as l, DEFAULT_EXTENSIONS as m, createLogger as n, CLIENT_PUBLIC_PATH as o, DEFAULT_DEV_PORT as p, printServerUrls as r, CSS_LANGS_RE as s, LogLevels as t, DEFAULT_CLIENT_CONDITIONS as u, DEFAULT_SERVER_MAIN_FIELDS as v, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR as w, ENV_ENTRY as x, DEP_VERSION_RE as y };