index.cjs 12 KB

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