index.cjs 12 KB

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