UNPKG

@storm-software/cloudflare-tools

Version:

A Nx plugin package that contains various executors, generators, and utilities that assist in managing Cloudflare services.

573 lines (562 loc) 18.4 kB
// ../config-tools/src/logger/console.ts import { formatDistanceToNow } from "date-fns/formatDistanceToNow"; // ../config-tools/src/types.ts var LogLevel = { SILENT: 0, FATAL: 10, ERROR: 20, WARN: 30, SUCCESS: 35, INFO: 40, PERFORMANCE: 50, DEBUG: 60, TRACE: 70, ALL: 100 }; var LogLevelLabel = { SILENT: "silent", FATAL: "fatal", ERROR: "error", WARN: "warn", SUCCESS: "success", INFO: "info", PERFORMANCE: "performance", DEBUG: "debug", TRACE: "trace", ALL: "all" }; // ../config-tools/src/utilities/colors.ts var DEFAULT_COLOR_CONFIG = { light: { background: "#fafafa", foreground: "#1d1e22", brand: "#1fb2a6", alternate: "#db2777", help: "#5C4EE5", success: "#087f5b", info: "#0550ae", debug: "#8afafc", warning: "#e3b341", danger: "#D8314A", fatal: "#51070f", performance: "#13c302", link: "#3fa6ff", positive: "#22c55e", negative: "#dc2626", gradient: ["#1fb2a6", "#db2777", "#5C4EE5"] }, dark: { background: "#1d1e22", foreground: "#cbd5e1", brand: "#2dd4bf", alternate: "#db2777", help: "#818cf8", success: "#10b981", info: "#58a6ff", debug: "#8afafc", warning: "#f3d371", danger: "#D8314A", fatal: "#a40e26", performance: "#80fd74", link: "#3fa6ff", positive: "#22c55e", negative: "#dc2626", gradient: ["#1fb2a6", "#db2777", "#818cf8"] } }; function getColors(config) { if (!config?.colors || typeof config.colors !== "object" || !config.colors["dark"] && (!config.colors["base"] || typeof config.colors !== "object" || !config.colors["base"]?.["dark"])) { return DEFAULT_COLOR_CONFIG; } if (config.colors["base"]) { if (typeof config.colors["base"]["dark"] === "object") { return config.colors["base"]["dark"]; } else if (config.colors["base"]["dark"] === "string") { return config.colors["base"]; } } if (typeof config.colors["dark"] === "object") { return config.colors["dark"]; } return config.colors ?? DEFAULT_COLOR_CONFIG; } function getColor(key, config) { const colors = getColors(config); const result = (typeof colors["dark"] === "object" ? colors["dark"][key] : colors[key]) || DEFAULT_COLOR_CONFIG["dark"][key] || DEFAULT_COLOR_CONFIG[key]; if (result) { return result; } if (key === "link" || key === "debug") { return getColor("info", config); } else if (key === "fatal") { return getColor("danger", config); } return getColor("brand", config); } // ../config-tools/src/logger/chalk.ts import chalk from "chalk"; var chalkDefault = { hex: (_) => (message) => message, bgHex: (_) => ({ whiteBright: (message) => message, white: (message) => message }), white: (message) => message, whiteBright: (message) => message, gray: (message) => message, bold: { hex: (_) => (message) => message, bgHex: (_) => ({ whiteBright: (message) => message, white: (message) => message }), whiteBright: (message) => message, white: (message) => message }, dim: { hex: (_) => (message) => message, gray: (message) => message } }; var getChalk = () => { let _chalk = chalk; if (!_chalk?.hex || !_chalk?.bold?.hex || !_chalk?.bgHex || !_chalk?.whiteBright || !_chalk?.white) { _chalk = chalkDefault; } return _chalk; }; // ../config-tools/src/logger/is-unicode-supported.ts function isUnicodeSupported() { if (process.platform !== "win32") { return process.env.TERM !== "linux"; } return Boolean(process.env.WT_SESSION) || // Windows Terminal Boolean(process.env.TERMINUS_SUBLIME) || // Terminus (<0.2.27) process.env.ConEmuTask === "{cmd::Cmder}" || // ConEmu and cmder process.env.TERM_PROGRAM === "Terminus-Sublime" || process.env.TERM_PROGRAM === "vscode" || process.env.TERM === "xterm-256color" || process.env.TERM === "alacritty" || process.env.TERM === "rxvt-unicode" || process.env.TERM === "rxvt-unicode-256color" || process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"; } // ../config-tools/src/logger/console-icons.ts var useIcon = (c, fallback) => isUnicodeSupported() ? c : fallback; var CONSOLE_ICONS = { [LogLevelLabel.ERROR]: useIcon("\u2718", "\xD7"), [LogLevelLabel.FATAL]: useIcon("\u{1F571}", "\xD7"), [LogLevelLabel.WARN]: useIcon("\u26A0", "\u203C"), [LogLevelLabel.INFO]: useIcon("\u2139", "i"), [LogLevelLabel.PERFORMANCE]: useIcon("\u23F1", "\u23F1"), [LogLevelLabel.SUCCESS]: useIcon("\u2714", "\u221A"), [LogLevelLabel.DEBUG]: useIcon("\u{1F6E0}", "D"), [LogLevelLabel.TRACE]: useIcon("\u2699", "T"), [LogLevelLabel.ALL]: useIcon("\u2709", "\u2192") }; // ../config-tools/src/logger/format-timestamp.ts var formatTimestamp = (fullDateTime = false, date = /* @__PURE__ */ new Date()) => { return fullDateTime ? `${date.toLocaleDateString()} ${date.toLocaleTimeString()}` : `${date.toLocaleTimeString()}`; }; // ../config-tools/src/logger/get-log-level.ts var getLogLevel = (label) => { switch (label) { case "all": return LogLevel.ALL; case "trace": return LogLevel.TRACE; case "debug": return LogLevel.DEBUG; case "performance": return LogLevel.PERFORMANCE; case "info": return LogLevel.INFO; case "warn": return LogLevel.WARN; case "error": return LogLevel.ERROR; case "fatal": return LogLevel.FATAL; case "silent": return LogLevel.SILENT; default: return LogLevel.INFO; } }; var getLogLevelLabel = (logLevel = LogLevel.INFO) => { if (logLevel >= LogLevel.ALL) { return LogLevelLabel.ALL; } if (logLevel >= LogLevel.TRACE) { return LogLevelLabel.TRACE; } if (logLevel >= LogLevel.DEBUG) { return LogLevelLabel.DEBUG; } if (logLevel >= LogLevel.PERFORMANCE) { return LogLevelLabel.PERFORMANCE; } if (logLevel >= LogLevel.INFO) { return LogLevelLabel.INFO; } if (logLevel >= LogLevel.WARN) { return LogLevelLabel.WARN; } if (logLevel >= LogLevel.ERROR) { return LogLevelLabel.ERROR; } if (logLevel >= LogLevel.FATAL) { return LogLevelLabel.FATAL; } if (logLevel <= LogLevel.SILENT) { return LogLevelLabel.SILENT; } return LogLevelLabel.INFO; }; // ../config-tools/src/logger/console.ts var getLogFn = (logLevel = LogLevel.INFO, config = {}, options = {}) => { const { chalk: _chalk = getChalk(), fullDateTime = false, hideDateTime = false } = options; const colors = !config.colors?.dark && !config.colors?.["base"] && !config.colors?.["base"]?.dark ? DEFAULT_COLOR_CONFIG : config.colors?.dark && typeof config.colors.dark === "string" ? config.colors : config.colors?.["base"]?.dark && typeof config.colors["base"].dark === "string" ? config.colors["base"].dark : config.colors?.["base"] ? config.colors?.["base"] : DEFAULT_COLOR_CONFIG; const configLogLevel = config.logLevel || process.env.STORM_LOG_LEVEL || LogLevelLabel.INFO; if (logLevel > getLogLevel(configLogLevel) || logLevel <= LogLevel.SILENT || getLogLevel(configLogLevel) <= LogLevel.SILENT) { return (_) => { }; } if (typeof logLevel === "number" && LogLevel.FATAL >= logLevel) { return (message) => { console.error( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.fatal ?? DEFAULT_COLOR_CONFIG.dark.fatal)( `[${CONSOLE_ICONS[LogLevelLabel.FATAL]} Fatal] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.ERROR >= logLevel) { return (message) => { console.error( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.danger ?? DEFAULT_COLOR_CONFIG.dark.danger)( `[${CONSOLE_ICONS[LogLevelLabel.ERROR]} Error] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.WARN >= logLevel) { return (message) => { console.warn( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.warning ?? DEFAULT_COLOR_CONFIG.dark.warning)( `[${CONSOLE_ICONS[LogLevelLabel.WARN]} Warn] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.SUCCESS >= logLevel) { return (message) => { console.info( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.success ?? DEFAULT_COLOR_CONFIG.dark.success)( `[${CONSOLE_ICONS[LogLevelLabel.SUCCESS]} Success] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.INFO >= logLevel) { return (message) => { console.info( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.info ?? DEFAULT_COLOR_CONFIG.dark.info)( `[${CONSOLE_ICONS[LogLevelLabel.INFO]} Info] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.PERFORMANCE >= logLevel) { return (message) => { console.debug( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.performance ?? DEFAULT_COLOR_CONFIG.dark.performance)( `[${CONSOLE_ICONS[LogLevelLabel.PERFORMANCE]} Performance] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.DEBUG >= logLevel) { return (message) => { console.debug( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.debug ?? DEFAULT_COLOR_CONFIG.dark.debug)( `[${CONSOLE_ICONS[LogLevelLabel.DEBUG]} Debug] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } if (typeof logLevel === "number" && LogLevel.TRACE >= logLevel) { return (message) => { console.debug( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex("#bbbbbb")( `[${CONSOLE_ICONS[LogLevelLabel.TRACE]} Trace] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; } return (message) => { console.log( ` ${hideDateTime ? "" : `${_chalk.gray(formatTimestamp(fullDateTime))} `}${_chalk.hex(colors.brand ?? DEFAULT_COLOR_CONFIG.dark.brand)( `[${CONSOLE_ICONS[LogLevelLabel.ALL]} System] ` )}${_chalk.bold.whiteBright(formatLogMessage(message))} ` ); }; }; var writeFatal = (message, config) => getLogFn(LogLevel.FATAL, config)(message); var writeError = (message, config) => getLogFn(LogLevel.ERROR, config)(message); var writeWarning = (message, config) => getLogFn(LogLevel.WARN, config)(message); var writeInfo = (message, config) => getLogFn(LogLevel.INFO, config)(message); var writeSuccess = (message, config) => getLogFn(LogLevel.SUCCESS, config)(message); var writePerformance = (message, config) => getLogFn(LogLevel.PERFORMANCE, config)(message); var writeDebug = (message, config) => getLogFn(LogLevel.DEBUG, config)(message); var writeTrace = (message, config) => getLogFn(LogLevel.TRACE, config)(message); var getStopwatch = (name) => { const start = /* @__PURE__ */ new Date(); return () => { writePerformance( `The${name ? ` ${name}` : ""} process took ${formatDistanceToNow(start, { includeSeconds: true })} to complete` ); }; }; var MAX_DEPTH = 10; var formatLogMessage = (message, options = {}, depth = 0) => { if (depth > MAX_DEPTH) { return "<max depth>"; } const prefix = options.prefix ?? ""; const skip = options.skip ?? []; const sort = options.sort ?? true; return typeof message === "undefined" || message === null ? "<empty>" : typeof message === "string" ? !message ? "<empty string>" : message : Array.isArray(message) ? ` ${message.sort( sort ? (a, b) => !a && !b ? 0 : !a ? 1 : !b ? -1 : String(a).localeCompare(String(b)) : void 0 ).map( (item, index) => ` ${prefix}> #${index} = ${formatLogMessage( item, { prefix: `${prefix}--`, skip, sort }, depth + 1 )}` ).join("\n")}` : typeof message === "object" ? ` ${Object.keys(message).filter( (key) => typeof key !== "string" || !skip.map((k) => k.toLowerCase().trim()).includes(key.toLowerCase().trim()) ).sort( sort ? (a, b) => !a && !b ? 0 : !a ? 1 : !b ? -1 : String(a).localeCompare(String(b)) : void 0 ).map( (key) => ` ${prefix}> ${key} = ${_isFunction(message[key]) ? "<function>" : typeof message[key] === "object" ? Object.keys(message[key]).filter( (key2) => typeof key2 !== "string" || !skip.map((k) => k.toLowerCase().trim()).includes(key2.toLowerCase().trim()) ).length === 0 ? "{}" : formatLogMessage( message[key], { prefix: `${prefix}--`, skip, sort }, depth + 1 ) : message[key]}` ).join("\n")}` : String(message); }; var _isFunction = (value) => { try { return value instanceof Function || typeof value === "function" || !!(value?.constructor && value?.call && value?.apply); } catch { return false; } }; var brandIcon = (config = {}, _chalk = getChalk()) => _chalk.hex(getColor("brand", config))("\u{1F5F2}"); // ../config-tools/src/utilities/correct-paths.ts var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; function normalizeWindowsPath(input = "") { if (!input) { return input; } return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); } var _UNC_REGEX = /^[/\\]{2}/; var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; var _DRIVE_LETTER_RE = /^[A-Za-z]:$/; var _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/; var correctPaths = function(path) { if (!path || path.length === 0) { return "."; } path = normalizeWindowsPath(path); const isUNCPath = path?.match(_UNC_REGEX); const isPathAbsolute = isAbsolute(path); const trailingSeparator = path[path.length - 1] === "/"; path = normalizeString(path, !isPathAbsolute); if (path.length === 0) { if (isPathAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } if (_DRIVE_LETTER_RE.test(path)) { path += "/"; } if (isUNCPath) { if (!isPathAbsolute) { return `//./${path}`; } return `//${path}`; } return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }; var joinPaths = function(...segments) { let path = ""; for (const seg of segments) { if (!seg) { continue; } if (path.length > 0) { const pathTrailing = path[path.length - 1] === "/"; const segLeading = seg[0] === "/"; const both = pathTrailing && segLeading; if (both) { path += seg.slice(1); } else { path += pathTrailing || segLeading ? seg : `/${seg}`; } } else { path += seg; } } return correctPaths(path); }; function cwd() { if (typeof process !== "undefined" && typeof process.cwd === "function") { return process.cwd().replace(/\\/g, "/"); } return "/"; } var resolve = function(...arguments_) { arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); let resolvedPath = ""; let resolvedAbsolute = false; for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { const path = index >= 0 ? arguments_[index] : cwd(); if (!path || path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = isAbsolute(path); } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute && !isAbsolute(resolvedPath)) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) { } else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } var isAbsolute = function(p) { return _IS_ABSOLUTE_RE.test(p); }; var relative = function(from, to) { const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"); const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/"); if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) { return _to.join("/"); } const _fromCopy = [..._from]; for (const segment of _fromCopy) { if (_to[0] !== segment) { break; } _from.shift(); _to.shift(); } return [..._from.map(() => ".."), ..._to].join("/"); }; export { LogLevel, getLogLevel, getLogLevelLabel, writeFatal, writeError, writeWarning, writeInfo, writeSuccess, writeDebug, writeTrace, getStopwatch, formatLogMessage, brandIcon, correctPaths, joinPaths, isAbsolute, relative };