index.cjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. // src/index.js
  20. var index_exports = {};
  21. __export(index_exports, {
  22. DEFAULT_OFFSET_STEP_SPACES: () => DEFAULT_OFFSET_STEP_SPACES,
  23. INSPECT_OPTIONS: () => INSPECT_OPTIONS,
  24. createColorizedDump: () => createColorizedDump,
  25. createDebugger: () => createDebugger
  26. });
  27. module.exports = __toCommonJS(index_exports);
  28. // src/create-debugger.js
  29. var import_js_format = require("@e22m4u/js-format");
  30. var import_js_format2 = require("@e22m4u/js-format");
  31. // src/utils/is-non-array-object.js
  32. function isNonArrayObject(input) {
  33. return Boolean(input && typeof input === "object" && !Array.isArray(input));
  34. }
  35. __name(isNonArrayObject, "isNonArrayObject");
  36. // src/utils/generate-random-hex.js
  37. function generateRandomHex(length = 4) {
  38. if (length <= 0) {
  39. return "";
  40. }
  41. const firstCharCandidates = "abcdef";
  42. const restCharCandidates = "0123456789abcdef";
  43. let result = "";
  44. const firstCharIndex = Math.floor(Math.random() * firstCharCandidates.length);
  45. result += firstCharCandidates[firstCharIndex];
  46. for (let i = 1; i < length; i++) {
  47. const randomIndex = Math.floor(Math.random() * restCharCandidates.length);
  48. result += restCharCandidates[randomIndex];
  49. }
  50. return result;
  51. }
  52. __name(generateRandomHex, "generateRandomHex");
  53. // src/create-colorized-dump.js
  54. var import_util = require("util");
  55. var INSPECT_OPTIONS = {
  56. showHidden: false,
  57. depth: null,
  58. colors: true,
  59. compact: false
  60. };
  61. function createColorizedDump(value) {
  62. return (0, import_util.inspect)(value, INSPECT_OPTIONS);
  63. }
  64. __name(createColorizedDump, "createColorizedDump");
  65. // src/create-debugger.js
  66. var AVAILABLE_COLORS = [
  67. 20,
  68. 21,
  69. 26,
  70. 27,
  71. 32,
  72. 33,
  73. 38,
  74. 39,
  75. 40,
  76. 41,
  77. 42,
  78. 43,
  79. 44,
  80. 45,
  81. 56,
  82. 57,
  83. 62,
  84. 63,
  85. 68,
  86. 69,
  87. 74,
  88. 75,
  89. 76,
  90. 77,
  91. 78,
  92. 79,
  93. 80,
  94. 81,
  95. 92,
  96. 93,
  97. 98,
  98. 99,
  99. 112,
  100. 113,
  101. 128,
  102. 129,
  103. 134,
  104. 135,
  105. 148,
  106. 149,
  107. 160,
  108. 161,
  109. 162,
  110. 163,
  111. 164,
  112. 165,
  113. 166,
  114. 167,
  115. 168,
  116. 169,
  117. 170,
  118. 171,
  119. 172,
  120. 173,
  121. 178,
  122. 179,
  123. 184,
  124. 185,
  125. 196,
  126. 197,
  127. 198,
  128. 199,
  129. 200,
  130. 201,
  131. 202,
  132. 203,
  133. 204,
  134. 205,
  135. 206,
  136. 207,
  137. 208,
  138. 209,
  139. 214,
  140. 215,
  141. 220,
  142. 221
  143. ];
  144. var DEFAULT_OFFSET_STEP_SPACES = 2;
  145. function pickColorCode(input) {
  146. if (typeof input !== "string")
  147. throw new import_js_format.Errorf(
  148. 'The parameter "input" of the function pickColorCode must be a String, but %v given.',
  149. input
  150. );
  151. let hash = 0;
  152. for (let i = 0; i < input.length; i++) {
  153. hash = (hash << 5) - hash + input.charCodeAt(i);
  154. hash |= 0;
  155. }
  156. return AVAILABLE_COLORS[Math.abs(hash) % AVAILABLE_COLORS.length];
  157. }
  158. __name(pickColorCode, "pickColorCode");
  159. function wrapStringByColorCode(input, color) {
  160. if (typeof input !== "string")
  161. throw new import_js_format.Errorf(
  162. 'The parameter "input" of the function wrapStringByColorCode must be a String, but %v given.',
  163. input
  164. );
  165. if (typeof color !== "number")
  166. throw new import_js_format.Errorf(
  167. 'The parameter "color" of the function wrapStringByColorCode must be a Number, but %v given.',
  168. color
  169. );
  170. const colorCode = "\x1B[3" + (Number(color) < 8 ? color : "8;5;" + color);
  171. return `${colorCode};1m${input}\x1B[0m`;
  172. }
  173. __name(wrapStringByColorCode, "wrapStringByColorCode");
  174. function matchPattern(pattern, input) {
  175. if (typeof pattern !== "string")
  176. throw new import_js_format.Errorf(
  177. 'The parameter "pattern" of the function matchPattern must be a String, but %v given.',
  178. pattern
  179. );
  180. if (typeof input !== "string")
  181. throw new import_js_format.Errorf(
  182. 'The parameter "input" of the function matchPattern must be a String, but %v given.',
  183. input
  184. );
  185. const regexpStr = pattern.replace(/\*/g, ".*?");
  186. const regexp = new RegExp("^" + regexpStr + "$");
  187. return regexp.test(input);
  188. }
  189. __name(matchPattern, "matchPattern");
  190. function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
  191. if (namespaceOrOptions && typeof namespaceOrOptions !== "string" && !isNonArrayObject(namespaceOrOptions)) {
  192. throw new import_js_format.Errorf(
  193. 'The parameter "namespace" of the function createDebugger must be a String or an Object, but %v given.',
  194. namespaceOrOptions
  195. );
  196. }
  197. const withCustomState = isNonArrayObject(namespaceOrOptions);
  198. const state = withCustomState ? namespaceOrOptions : {};
  199. state.envNsSegments = Array.isArray(state.envNsSegments) ? state.envNsSegments : [];
  200. state.nsSegments = Array.isArray(state.nsSegments) ? state.nsSegments : [];
  201. state.pattern = typeof state.pattern === "string" ? state.pattern : "";
  202. state.hash = typeof state.hash === "string" ? state.hash : "";
  203. state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
  204. state.offsetStep = typeof state.offsetStep !== "string" ? " ".repeat(DEFAULT_OFFSET_STEP_SPACES) : state.offsetStep;
  205. state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
  206. if (!withCustomState) {
  207. if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
  208. state.envNsSegments.push(process.env.DEBUGGER_NAMESPACE);
  209. }
  210. if (typeof namespaceOrOptions === "string")
  211. state.nsSegments.push(namespaceOrOptions);
  212. }
  213. namespaceSegments.forEach((segment) => {
  214. if (!segment || typeof segment !== "string")
  215. throw new import_js_format.Errorf(
  216. "Namespace segment must be a non-empty String, but %v given.",
  217. segment
  218. );
  219. state.nsSegments.push(segment);
  220. });
  221. if (typeof process !== "undefined" && process.env && process.env["DEBUG"]) {
  222. state.pattern = process.env["DEBUG"];
  223. } else if (typeof localStorage !== "undefined" && typeof localStorage.getItem("debug") === "string") {
  224. state.pattern = localStorage.getItem("debug");
  225. }
  226. const isDebuggerEnabled = /* @__PURE__ */ __name(() => {
  227. const nsStr = [...state.envNsSegments, ...state.nsSegments].join(
  228. state.delimiter
  229. );
  230. const patterns = state.pattern.split(/[\s,]+/).filter((p) => p.length > 0);
  231. if (patterns.length === 0 && state.pattern !== "*") return false;
  232. for (const singlePattern of patterns) {
  233. if (matchPattern(singlePattern, nsStr)) return true;
  234. }
  235. return false;
  236. }, "isDebuggerEnabled");
  237. const getPrefix = /* @__PURE__ */ __name(() => {
  238. let tokens = [];
  239. [...state.envNsSegments, ...state.nsSegments, state.hash].filter(Boolean).forEach((token) => {
  240. const extractedTokens = token.split(state.delimiter).filter(Boolean);
  241. tokens = [...tokens, ...extractedTokens];
  242. });
  243. let res = tokens.reduce((acc, token, index) => {
  244. const isLast = tokens.length - 1 === index;
  245. const tokenColor = pickColorCode(token);
  246. acc += wrapStringByColorCode(token, tokenColor);
  247. if (!isLast) acc += state.delimiter;
  248. return acc;
  249. }, "");
  250. if (state.offsetSize > 0) res += state.offsetStep.repeat(state.offsetSize);
  251. return res;
  252. }, "getPrefix");
  253. function debugFn(messageOrData, ...args) {
  254. if (!isDebuggerEnabled()) return;
  255. const prefix = getPrefix();
  256. const multiString = (0, import_js_format2.format)(messageOrData, ...args);
  257. const rows = multiString.split("\n");
  258. rows.forEach((message) => {
  259. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  260. });
  261. }
  262. __name(debugFn, "debugFn");
  263. debugFn.withNs = function(namespace, ...args) {
  264. const stateCopy = JSON.parse(JSON.stringify(state));
  265. [namespace, ...args].forEach((ns) => {
  266. if (!ns || typeof ns !== "string")
  267. throw new import_js_format.Errorf(
  268. "Debugger namespace must be a non-empty String, but %v given.",
  269. ns
  270. );
  271. stateCopy.nsSegments.push(ns);
  272. });
  273. return createDebugger(stateCopy);
  274. };
  275. debugFn.withHash = function(hashLength = 4) {
  276. const stateCopy = JSON.parse(JSON.stringify(state));
  277. if (!hashLength || typeof hashLength !== "number" || hashLength < 1) {
  278. throw new import_js_format.Errorf(
  279. "Debugger hash must be a positive Number, but %v given.",
  280. hashLength
  281. );
  282. }
  283. stateCopy.hash = generateRandomHex(hashLength);
  284. return createDebugger(stateCopy);
  285. };
  286. debugFn.withOffset = function(offsetSize) {
  287. const stateCopy = JSON.parse(JSON.stringify(state));
  288. if (!offsetSize || typeof offsetSize !== "number" || offsetSize < 1) {
  289. throw new import_js_format.Errorf(
  290. "Debugger offset must be a positive Number, but %v given.",
  291. offsetSize
  292. );
  293. }
  294. stateCopy.offsetSize = offsetSize;
  295. return createDebugger(stateCopy);
  296. };
  297. debugFn.withoutEnvNs = function() {
  298. const stateCopy = JSON.parse(JSON.stringify(state));
  299. stateCopy.envNsSegments = [];
  300. return createDebugger(stateCopy);
  301. };
  302. debugFn.inspect = function(valueOrDesc, ...args) {
  303. if (!isDebuggerEnabled()) return;
  304. const prefix = getPrefix();
  305. let multiString = "";
  306. if (typeof valueOrDesc === "string" && args.length) {
  307. multiString += `${valueOrDesc}
  308. `;
  309. const multilineDump = args.map((v) => createColorizedDump(v)).join("\n");
  310. const dumpRows = multilineDump.split("\n");
  311. multiString += dumpRows.map((v) => `${state.offsetStep}${v}`).join("\n");
  312. } else {
  313. multiString += [valueOrDesc, ...args].map((v) => createColorizedDump(v)).join("\n");
  314. }
  315. const rows = multiString.split("\n");
  316. rows.forEach((message) => {
  317. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  318. });
  319. };
  320. return debugFn;
  321. }
  322. __name(createDebugger, "createDebugger");
  323. // Annotate the CommonJS export names for ESM import in node:
  324. 0 && (module.exports = {
  325. DEFAULT_OFFSET_STEP_SPACES,
  326. INSPECT_OPTIONS,
  327. createColorizedDump,
  328. createDebugger
  329. });