index.cjs 12 KB

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