index.cjs 12 KB

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