index.cjs 12 KB

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