UNPKG

nsole

Version:

A drop-in isomorphic console.* replacement that's pretty, small, fast, and flexible

516 lines (510 loc) 17.2 kB
var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __hasOwnProp = Object.prototype.hasOwnProperty; var __moduleCache = /* @__PURE__ */ new WeakMap; var __toCommonJS = (from) => { var entry = __moduleCache.get(from), desc; if (entry) return entry; entry = __defProp({}, "__esModule", { value: true }); if (from && typeof from === "object" || typeof from === "function") __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })); __moduleCache.set(from, entry); return entry; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, set: (newValue) => all[name] = () => newValue }); }; // src/node/etag.ts var exports_etag = {}; __export(exports_etag, { etag: () => etag, default: () => etag_default }); module.exports = __toCommonJS(exports_etag); // src/constants.ts var ANSI_NONE = "rgba(0,0,0,0.0)"; // src/node/_utils_.ts var ANSI_TUPLE = [ [ 0, 0, 0 ], [ 128, 0, 0 ], [ 0, 128, 0 ], [ 128, 128, 0 ], [ 0, 0, 128 ], [ 128, 0, 128 ], [ 0, 128, 128 ], [ 192, 192, 192 ], [ 128, 128, 128 ], [ 255, 0, 0 ], [ 0, 255, 0 ], [ 255, 255, 0 ], [ 0, 0, 255 ], [ 255, 0, 255 ], [ 0, 255, 255 ], [ 255, 255, 255 ] ]; var ANSI_TUPLE_RBGA = [ "rgba(0,0,0,1.0)", "rgba(128,0,0,1.0)", "rgba(0,128,0,1.0)", "rgba(128,128,0,1.0)", "rgba(0,0,128,1.0)", "rgba(128,0,128,1.0)", "rgba(0,128,128,1.0)", "rgba(192,192,192,1.0)", "rgba(128,128,128,1.0)", "rgba(255,0,0,1.0)", "rgba(0,255,0,1.0)", "rgba(255,255,0,1.0)", "rgba(0,0,255,1.0)", "rgba(255,0,255,1.0)", "rgba(0,255,255,1.0)", "rgba(255,255,255,1.0)" ]; typeof PTAG_WINDOW === "undefined" && typeof globalThis !== "object" && function(Object2) { function get() { var e = this || self; e.globalThis = e, delete Object2.prototype._T_; } typeof globalThis != "object" && (this ? get() : (Object2.defineProperty(Object2.prototype, "_T_", { configurable: true, get }), _T_)); }(Object); var PROC_ENV = /* @__PURE__ */ (() => typeof process === "undefined" ? {} : !globalThis?.["Deno"] ? process["env"] : (() => { try { return process["env"]?.toObject ? process["env"]?.toObject() : process["env"]; } catch (_err) {} return {}; })())(); var ARGV = /* @__PURE__ */ (() => typeof process === "undefined" ? typeof scriptArgs !== "undefined" ? scriptArgs : [] : (globalThis?.["Deno"] ? process["args"]?.length ? process["args"] : process["argv"] : process["argv"]) ?? [])(); var hasArgv = (key, argv = ARGV) => !argv?.length ? false : new RegExp(`(^|[^\\S])(?:--|-)${key}(=|\\s|$)`, "i").test(argv.join(" ")); var getArgvValue = (key, argv = ARGV) => !argv?.length ? null : ` ${argv.join(" ")} `.match(new RegExp(`(^|[\\s])(?:--|-)${key}(?:=|\\s+)(['"]?)([^-\\s][^'"-\\s]*?|(?:\\D?[^-].*?))\\2(?:\\s|$)`, "i"))?.[3]?.replace(/^(''|"")$/, "") ?? null; var getArgv = /* @__PURE__ */ (() => { const cache = {}; return (key, argv = ARGV) => { if (key in cache) { return cache[key] ?? null; } const res = !argv?.length ? null : hasArgv(key, argv) ? getArgvValue(key, argv) ?? "" : hasArgv(key.replaceAll("_", "-"), argv) ? getArgvValue(key.replaceAll("_", "-"), argv) ?? "" : null; if (true) { cache[key] = res; } return res; }; })(); var getEnvVar = (key, argv = ARGV, procEnv = PROC_ENV, gthis = globalThis) => getArgv(key, argv) ?? (key in procEnv ? procEnv[key] : (key in gthis) ? gthis[key] : null) ?? null; var getEnvRaw = (key) => getEnvVar(`${"PTAG_"}${key}_FORCE`) ?? getEnvVar(`${"PTAG_"}${key}`) ?? null; var getEnvDefVal = ([key, param, def], idx, _ignore = [], dval = def ?? null) => { const pkey = `${"PTAG_"}${key}`; const fkey = `${"PTAG_"}${key}_FORCE`; const fval = getEnvVar(fkey) ?? null; if (key === "PLG") { return [ param ?? globalThis[pkey] ?? dval, fval ]; } const pval = param ?? getEnvVar(pkey) ?? dval; if (key === "ID" || key === "FG") { return [pval, fval]; } if (key === "LVL") { let lvl = pval === null ? 5 : Number(Number.parseInt(`${pval}`)); const flvl = fval !== null ? Number(Number.parseInt(`${fval}`)) : null; if (Number.isNaN(lvl)) { console.error([ `[ptag:getEnvDefVal] bad log level value NaN; ignoring/defaulting to 5`, ` key: ${key}`, `value: ${fval}` ].join(` `)); lvl = 5; } return [lvl, flvl]; } if (key === "DEF") { return [pval, fval].map((val, sidx) => { const nov = !sidx ? dval : null; if (typeof val !== "string") { return val ?? nov; } try { return JSON.parse(val) ?? nov; } catch (err) { console.error([ `[ptag:getEnvDefVal] JSON.parse error`, ` key: ${key}${sidx ? "(force)" : ""}`, `value: ${val}`, `error: ` + ((err instanceof Error ? err.message : null) ?? "unknown error") ].join(` `)); } return dval; }); } return [dval, fval]; }; var COLOR_SPACE = /* @__PURE__ */ (() => { try { const colorSpaces = [0, 1, 2, 3]; const toSpace = (val) => val === undefined || val === null ? null : colorSpaces[colorSpaces.indexOf(Number.parseInt(String(val)))] ?? null; const forceColor = getEnvVar("FORCE_COLOR"); const isForced = forceColor === "" ? 3 : toSpace(forceColor) ?? toSpace(getEnvVar("PTAG_COLOR")); if (isForced !== null) { return isForced; } if (typeof process === "undefined") { return 0; } const { COLORTERM, TERM, CI, PM2_HOME, pm_id } = PROC_ENV; const noColor = getEnvVar("NO_COLOR") !== null || getEnvVar("NODE_DISABLE_COLORS") !== null || /-mono|dumb/i.test(TERM ?? ""); if (noColor) { return 0; } const isTTY = !!process.stdout?.isTTY || !!PM2_HOME && !!pm_id || (globalThis?.["Deno"] ? globalThis?.["Deno"]?.isatty(1) : !!process.stdout?.isTTY); if (!isTTY) { return 0; } let argvColorRaw = getArgvValue("color"); const argvColor = argvColorRaw ? toSpace(argvColorRaw) ?? (/^(false|never|no|0)$/i.test(`${argvColorRaw}`.trim()) ? 0 : null) : null; if (argvColor !== null) { return argvColor; } if (CI) { return 1; } return COLORTERM === "truecolor" || COLORTERM === "24bit" || TERM && /^xterm-(kitty|direct)$/i.test(TERM) ? 3 : COLORTERM === "ansi256" || COLORTERM === "8bit" || TERM && /-256(colou?r)?$/i.test(TERM) ? 2 : 1; } catch (_err) {} return 0; })(); var escAnsi = (str, open, close, replace, colorSpace = 0) => { if (!colorSpace) { return str; } open = `\x1B[${open}m`; close = `\x1B[${close}m`; let idx = str.indexOf(close, open.length); if (!~idx) { return open + str + close; } let rclose = ""; let cursor = 0; replace = replace ? `\x1B[22m\x1B[${replace}m` : open; do { rclose += str.substring(cursor, idx) + replace; cursor = idx + close.length; idx = str.indexOf(close, cursor); } while (~idx); return open + rclose + str.substring(cursor) + close; }; var parseHexColor = (color) => { let hexClean = color.replace(/^#/, ""); if (![3, 4, 6, 8].includes(hexClean.length)) { return [0, 0, 0, -255]; } return hexClean.length === 3 ? [ ...[...hexClean].flatMap((c) => [c, c]).join("").match(/.{2}/g)?.map((v) => Number.parseInt(v, 16)) || [0, 0, 0], 255 ] : hexClean.length === 4 ? [...hexClean.slice(0, 4)].flatMap((c) => [c, c]).join("").match(/.{2}/g)?.map((v) => Number.parseInt(v, 16)) || [0, 0, 0, 255] : hexClean.length === 8 ? hexClean.match(/.{2}/g)?.map((v) => Number.parseInt(v, 16)) || [0, 0, 0, 255] : [ ...hexClean.substring(0, 6).match(/.{2}/g)?.map((v) => Number.parseInt(v, 16)) || [0, 0, 0], 255 ]; }; var REGEX_RGB = /rgba?\(\s*([\d.]+%?)\s*(?:,\s*|\s+)([\d.]+%?)\s*(?:,\s*|\s+)([\d.]+%?)(?:\s*(?:\/|,)\s*([\d.]+%?))?\s*\)/i; var parseRgbColor = (color) => { const result = color.match(REGEX_RGB); return !result ? [0, 0, 0, -255] : [ ...result.slice(1, 4).map((comp) => comp.trim().endsWith("%") ? Math.round(Number.parseFloat(comp) * 2.55) : Number.parseInt(comp, 10)), result[4] ? result[4].trim().endsWith("%") ? Math.round(Number.parseFloat(result[4]) * 2.55) : Math.round(Number.parseFloat(result[4]) * 255) : 255 ]; }; var parseHslColor = (color) => { const separator = color.indexOf(",") > -1 ? "," : " "; let hslValues = color.replace(/hsla?\(/i, "").replace("/", " ").split(")")?.[0]?.split(separator)?.filter(Boolean); if (!hslValues || 2 >= hslValues.length) { return [0, 0, 0, -255]; } let alpha = 255; if (hslValues.length >= 4) { const alphaStr = hslValues.pop(); alpha = alphaStr.endsWith("%") ? Math.round(Number.parseFloat(alphaStr) * 2.55) : Math.round(Number.parseFloat(alphaStr) * 255); } let shue = hslValues.shift().trim(); shue = shue.endsWith("deg") ? shue.replace("deg", "") : shue.endsWith("rad") ? String(Math.round(Number.parseFloat(shue.replace("rad", "")) * (180 / Math.PI))) : shue.endsWith("turn") ? String(Math.round(Number.parseFloat(shue.replace("turn", "")) * 360)) : shue; let [h, s, l] = [shue, ...hslValues].map((v) => { const n = Number.parseFloat(v.replace("%", "") ?? "0"); return Number.isFinite(n) ? n : 0; }); s = Math.max(0, Math.min(100, s)) / 100; l = Math.max(0, Math.min(100, l)) / 100; if (l >= 1) { return [255, 255, 255, alpha]; } if (l === 0) { return [0, 0, 0, alpha]; } h = (h % 360 + 360) % 360; const c = (1 - Math.abs(2 * l - 1)) * s; const x = c * (1 - Math.abs(h / 60 % 2 - 1)); const m = l - c / 2; return (h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x]).map((v) => Math.round((v + m) * 255)).concat(alpha); }; var cssColorToRgb = (color) => { const trimmed = color.trim(); const rgba = /^#|^[0-9a-f]{3,8}$/i.test(trimmed) ? parseHexColor(trimmed) : /^rgba?\(/i.test(trimmed) ? parseRgbColor(trimmed) : /^hsla?\(/i.test(trimmed) ? parseHslColor(trimmed) : [0, 0, 0, -255]; rgba[3] = rgba[3] / 255; return rgba.find((v) => Number.isNaN(v)) ? [0, 0, 0, -1] : rgba; }; var _cssColorToAnsi = (color, isBg = 0, colorSpace = COLOR_SPACE) => { if (!colorSpace) { return ""; } const sweetSixteen = ANSI_TUPLE_RBGA.indexOf(color.trim()); if (sweetSixteen !== -1) { return String(sweetSixteen + (sweetSixteen >= 8 ? 82 : 30) + (isBg ? 10 : 0)); } const [r, g, b, alpha] = cssColorToRgb(color); if (0 >= alpha) { return ""; } if (colorSpace === 3) { return [isBg ? 48 : 38, "2", r, g, b].join(";"); } if (colorSpace === 1) { const ansi = ANSI_TUPLE.map(([sr, sg, sb], idx) => [ idx, Math.sqrt(Math.pow(r - sr, 2) + Math.pow(g - sg, 2) + Math.pow(b - sb, 2)) * ((!(r === g && g === b) && (sr === sg && sg === sb) ? 2 : 1) + (sg === 0 && sb === 0 && sr > 0 ? 0.1 : 0)) * (idx === 4 || idx === 12 ? r < 50 && g > 100 && g < 200 && b > 200 ? 0.5 : 1 : 1) ]).sort((a, b2) => a[1] - b2[1])[0]?.[0] ?? 0; return String(ansi + (ansi >= 8 ? 82 : 30) + (isBg ? 10 : 0)); } const res = r === g && g === b ? r < 8 ? 16 : r > 248 ? 231 : Math.round((r - 8) / 247 * 24) + 232 : 16 + [[36, r], [6, g], [1, b]].reduce((acc, [m, c]) => acc + m * Math.round(c / 255 * 5), 0); return [ isBg ? 48 : 38, 5, Number.isInteger(res) ? res : 0 ].join(";"); }; var cssColorToAnsi = /* @__PURE__ */ (() => { const cache = new Map; const keys = []; return (color, isBg = 0, colorSpace = COLOR_SPACE) => { const key = `${color}:${isBg}:${colorSpace}`; const prv = cache.get(key); if (prv) { return prv; } const result = _cssColorToAnsi(color, isBg, colorSpace); keys.length >= 100 && cache.delete(keys.shift()); keys.push(key); cache.set(key, result); return result; }; })(); var toAnsiFg = (str, hex, colorSpace = COLOR_SPACE) => escAnsi(str, cssColorToAnsi(hex, 0, colorSpace), "39", undefined, colorSpace); var toAnsiBg = (str, hex, colorSpace = COLOR_SPACE) => escAnsi(str, cssColorToAnsi(hex, 1, colorSpace), "49", undefined, colorSpace); var fromCssToAnsi = (str, css, colorSpace = COLOR_SPACE) => { if (!str || !css) { return str; } const ckv = css.split(";").filter(Boolean).map((val) => val.split(":").map((s) => s.trim())); const plast = { display: null, bg: null, background: null, fg: null, color: null, fw: null, "font-weight": null }; for (let i = ckv.length - 1;i >= 0; i--) { const key = ckv[i]?.[0]; if (!key) { continue; } if (plast[key] === null) { plast[key] = ckv[i]?.[1] ?? null; } } if (plast.display === "none") { return ""; } const bg = plast.bg ?? plast.background; const fg = plast.fg ?? plast.color; const fw = plast.fw ?? plast["font-weight"]; let ansi = str; if (fw && (fw === "bold" || Number(fw) > 500)) { ansi = escAnsi(ansi, 1, 22, 1, colorSpace); } ansi = !fg || fg === ANSI_NONE ? ansi : toAnsiFg(ansi, fg, colorSpace); ansi = !bg || bg === ANSI_NONE ? ansi : toAnsiBg(ansi, bg, colorSpace); return ansi; }; // src/node/_tmpl_.etag.ts var etag = (id, level, definitions, pluginFn, colorSpace, i = "_id", s = "_def", l = "_lvl", _G = "PTAG_", _F = "_FORCE", eobj = {}, lnoop = () => {}, tof = (v, k = "s") => (typeof v)[0] == k, _gthis = eobj, _getEnvDefVal = lnoop, [[idG, idF], [fgG, fgF], [lvlG, lvlF], [pluginG, pluginF], [defsG, defsF]] = [ ["ID", id, "{}"], ["FG"], ["LVL", level, 5], ["PLG", pluginFn], ["DEF", null, eobj] ].map(getEnvDefVal), _defs = { debug: [5, ">", "rgb(136,153,170)"], log: [4, ">", "rgb(34,170,238)"], info: [4, "i", "rgb(17,170,170)"], check: [3, "?", "rgb(221,102,221)"], warn: [2, "!", "rgb(255,119,119)"], error: [1, "X", "rgb(255,51,102)"], _dl: [ "", " ", " " ], _css: [ " ", " ", "color:^;", " ", `color:^^^;background:${"rgba(0,0,0,0.0)"};font-weight:${getEnvRaw("FW") ?? 900};` ], ...defsG, ...definitions ?? eobj, _fg: definitions?._fg ?? fgG ?? defsG?._fg ?? "rgba(0,0,0,0.0)", ...defsF ?? eobj }, setStyle = (value, dvalue = _defs) => ({ ...dvalue, ...value ?? _defs }), isForceRerun = 0 > colorSpace || Object.is(-0, colorSpace), colorSpaceParam = -3 > colorSpace ? undefined : colorSpace, gforceKey = _G + "LVL" + _F, gconsole = console) => new Proxy({ [i]: idG, [s]: setStyle(), [l]: lvlG }, { get: (target, prop) => { if (prop == l || prop == i || prop == s) { return target[prop]; } let defs = s in target ? target[s] : _defs; let idef = defs[prop]; let ilvl = target[l]; if (gforceKey in globalThis) { lvlF = globalThis[gforceKey]; ilvl = ~~(lvlF ?? target[l]); } if (ilvl && (ilvl == -1 || !idef && (prop in gconsole))) { return gconsole[prop] ?? gconsole.log; } let rtn = null; if (ilvl !== -2 && (!ilvl || idef?.[0] > ilvl)) { rtn = lnoop; } if (!rtn && ((target[prop] ?? lnoop) === lnoop || isForceRerun)) { target[s] = idef ? defs : setStyle({ [prop]: [1, prop, defs._fg] }, defs); idef = target[s][prop]; let cid = (idF ?? target[i] ?? "").replace("{}", prop); let plug = pluginF ?? pluginG; let [nid, tag, bg, fg, cm, css, dl] = plug ? plug(idef, prop, cid, target) : idef; if (nid !== idef[0]) { if (tof(nid, "f")) { return nid; } cid = tof(nid) ? nid : cid; } fg = defsF?._fg ?? fgF ?? fg; dl = defsF?._dl ?? dl ?? defs._dl; css = defsF?._css ?? css ?? defs._css; let nc = Math.abs(colorSpaceParam ?? ("NO_COLOR" in globalThis || (fg ?? defs._fg) == "" ? 0 : COLOR_SPACE)); let [ds, dm, de] = dl; let [dcss, tcss, xcss, ecss, acss] = css; [dcss, tcss, xcss, ecss] = [dcss, tcss, xcss, dcss + ecss].map((v) => v ? ((acss ?? "") + v).replace(/\^+/g, (match) => (match == "^" ? fg ?? bg : match == "^^" ? fg ?? defs._fg : bg) ?? "rgba(0,0,0,0.0)") : v); tag = fromCssToAnsi(prop === tag ? "*" : tag, tcss, nc); if (ds) { tag = fromCssToAnsi(ds, dcss, nc) + tag; } if (dm) { tag += fromCssToAnsi(dm, dcss, nc); } tag += fromCssToAnsi(cid, xcss, nc); if (de) { tag += fromCssToAnsi(de, ecss, nc); } target[prop] = ilvl === -2 ? (...args) => [tag, ...args] : (gconsole[cm ?? prop] ?? gconsole.log).bind(gconsole, tag); } return rtn || target[prop]; }, set: (target, prop, value) => { target[prop] = prop == l ? value ?? lvlG : prop == i ? value ?? idG : setStyle(value, target[s]); for (let k in target[s]) { target[k] = lnoop; } return true; } }); // src/node/etag.ts var etag_default = etag;