index.cjs 9.0 KB

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