index.cjs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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.nsSegments = Array.isArray(state.nsSegments) ? state.nsSegments : [];
  200. state.pattern = typeof state.pattern === "string" ? state.pattern : "";
  201. state.hash = typeof state.hash === "string" ? state.hash : "";
  202. state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
  203. state.offsetStep = typeof state.offsetStep !== "string" ? " ".repeat(DEFAULT_OFFSET_STEP_SPACES) : state.offsetStep;
  204. state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
  205. if (!withCustomState) {
  206. if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
  207. state.nsSegments.push(process.env.DEBUGGER_NAMESPACE);
  208. }
  209. if (typeof namespaceOrOptions === "string")
  210. state.nsSegments.push(namespaceOrOptions);
  211. }
  212. namespaceSegments.forEach((segment) => {
  213. if (!segment || typeof segment !== "string")
  214. throw new import_js_format.Errorf(
  215. "Namespace segment must be a non-empty String, but %v given.",
  216. segment
  217. );
  218. state.nsSegments.push(segment);
  219. });
  220. if (typeof process !== "undefined" && process.env && process.env["DEBUG"]) {
  221. state.pattern = process.env["DEBUG"];
  222. } else if (typeof localStorage !== "undefined" && typeof localStorage.getItem("debug") === "string") {
  223. state.pattern = localStorage.getItem("debug");
  224. }
  225. const isDebuggerEnabled = /* @__PURE__ */ __name(() => {
  226. const nsStr = state.nsSegments.join(state.delimiter);
  227. const patterns = state.pattern.split(/[\s,]+/).filter((p) => p.length > 0);
  228. if (patterns.length === 0 && state.pattern !== "*") return false;
  229. for (const singlePattern of patterns) {
  230. if (matchPattern(singlePattern, nsStr)) return true;
  231. }
  232. return false;
  233. }, "isDebuggerEnabled");
  234. const getPrefix = /* @__PURE__ */ __name(() => {
  235. let tokens = [];
  236. [...state.nsSegments, state.hash].filter(Boolean).forEach((token) => {
  237. const extractedTokens = token.split(state.delimiter).filter(Boolean);
  238. tokens = [...tokens, ...extractedTokens];
  239. });
  240. let res = tokens.reduce((acc, token, index) => {
  241. const isLast = tokens.length - 1 === index;
  242. const tokenColor = pickColorCode(token);
  243. acc += wrapStringByColorCode(token, tokenColor);
  244. if (!isLast) acc += state.delimiter;
  245. return acc;
  246. }, "");
  247. if (state.offsetSize > 0) res += state.offsetStep.repeat(state.offsetSize);
  248. return res;
  249. }, "getPrefix");
  250. function debugFn(messageOrData, ...args) {
  251. if (!isDebuggerEnabled()) return;
  252. const prefix = getPrefix();
  253. if (typeof messageOrData === "string") {
  254. const multiString2 = (0, import_js_format2.format)(messageOrData, ...args);
  255. const rows2 = multiString2.split("\n");
  256. rows2.forEach((message) => {
  257. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  258. });
  259. return;
  260. }
  261. const multiString = createColorizedDump(messageOrData);
  262. const rows = multiString.split("\n");
  263. if (args.length) {
  264. args.forEach((message) => {
  265. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  266. });
  267. rows.forEach((message) => {
  268. message = `${state.offsetStep}${message}`;
  269. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  270. });
  271. } else {
  272. rows.forEach((message) => {
  273. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  274. });
  275. }
  276. }
  277. __name(debugFn, "debugFn");
  278. debugFn.withNs = function(namespace, ...args) {
  279. const stateCopy = JSON.parse(JSON.stringify(state));
  280. [namespace, ...args].forEach((ns) => {
  281. if (!ns || typeof ns !== "string")
  282. throw new import_js_format.Errorf(
  283. "Debugger namespace must be a non-empty String, but %v given.",
  284. ns
  285. );
  286. stateCopy.nsSegments.push(ns);
  287. });
  288. return createDebugger(stateCopy);
  289. };
  290. debugFn.withHash = function(hashLength = 4) {
  291. const stateCopy = JSON.parse(JSON.stringify(state));
  292. if (!hashLength || typeof hashLength !== "number" || hashLength < 1) {
  293. throw new import_js_format.Errorf(
  294. "Debugger hash must be a positive Number, but %v given.",
  295. hashLength
  296. );
  297. }
  298. stateCopy.hash = generateRandomHex(hashLength);
  299. return createDebugger(stateCopy);
  300. };
  301. debugFn.withOffset = function(offsetSize) {
  302. const stateCopy = JSON.parse(JSON.stringify(state));
  303. if (!offsetSize || typeof offsetSize !== "number" || offsetSize < 1) {
  304. throw new import_js_format.Errorf(
  305. "Debugger offset must be a positive Number, but %v given.",
  306. offsetSize
  307. );
  308. }
  309. stateCopy.offsetSize = offsetSize;
  310. return createDebugger(stateCopy);
  311. };
  312. return debugFn;
  313. }
  314. __name(createDebugger, "createDebugger");
  315. // Annotate the CommonJS export names for ESM import in node:
  316. 0 && (module.exports = {
  317. DEFAULT_OFFSET_STEP_SPACES,
  318. INSPECT_OPTIONS,
  319. createColorizedDump,
  320. createDebugger
  321. });