analogger 1.8.4 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
- ## [1.8.4](https://github.com/thimpat/analogger/compare/v1.8.3...v1.8.4) (2022-02-28)
1
+ ## [1.9.1](https://github.com/thimpat/analogger/compare/v1.9.0...v1.9.1) (2022-03-14)
2
2
 
3
+ # [1.9.0](https://github.com/thimpat/analogger/compare/v1.8.5...v1.9.0) (2022-03-06)
4
+
5
+ ## [1.8.5](https://github.com/thimpat/analogger/compare/v1.8.4...v1.8.5) (2022-02-28)
6
+
7
+ ## [1.8.4](https://github.com/thimpat/analogger/compare/v1.8.3...v1.8.4) (2022-02-28)
8
+
3
9
  ## [1.8.3](https://github.com/thimpat/analogger/compare/v1.8.2...v1.8.3) (2022-02-28)
4
10
 
5
11
  ## [1.8.2](https://github.com/thimpat/analogger/compare/v1.8.1...v1.8.2) (2022-02-28)
package/README.md CHANGED
@@ -104,14 +104,14 @@ anaLogger.setOptions({hideHookMessage: true, logToDom: "#analogger"})
104
104
  ### overrideConsole()
105
105
 
106
106
  ```javascript
107
- anaLogger.setOptions({silent: false, hideError: false})
107
+ anaLogger.setOptions({silent: true, hideError: false})
108
108
  console.log(`Log Before override`);
109
109
  anaLogger.overrideConsole()
110
110
  console.log(`Log After override`);
111
111
  ```
112
112
 
113
113
  Override console.log, console.info and console.warn. If you already have many console.log running in your system,
114
- it allows formatting them or hiding then (silent = true) all in one go.
114
+ it allows hiding them all in one go.
115
115
  In this example, the terminal (or inspector) will not show the message "Log After override". All following messages
116
116
  either.
117
117
 
@@ -4,13 +4,26 @@
4
4
  * [./src/cjs/ana-logger.cjs]{@link ./src/cjs/ana-logger.cjs}
5
5
  *
6
6
  **/
7
- import toAnsi from "../../node_modules/to-ansi/index.mjs";
8
- import rgbHex from "../../node_modules/rgb-hex/index.mjs";
9
- import {COLOR_TABLE, SYSTEM} from "./constants.mjs";
7
+ import path from "path";
8
+ import fs from "fs";
9
+ import os from "os";
10
+ import toAnsi from "./node_modules/to-ansi/index.mjs";
11
+ import rgbHex from "./node_modules/rgb-hex/index.mjs";
12
+ import {COLOR_TABLE, SYSTEM} from "./src/cjs/constants.mjs";
13
+ import {stringify} from "./node_modules/flatted/cjs/index.mjs";
14
+ /** to-esm-browser: remove **/
10
15
 
11
16
 
12
17
 
13
18
 
19
+
20
+
21
+ const PREDEFINED_CONTEXT_NAMES = {
22
+ "DEFAULT": "DEFAULT",
23
+ "ERROR": "ERROR"
24
+ };
25
+
26
+
14
27
  const EOL =`
15
28
  `;
16
29
 
@@ -214,12 +227,17 @@ class AnaLogger
214
227
  {
215
228
  this.options.logToFile = logToFile || "./analogger.log";
216
229
 
217
-
230
+ /** to-esm-browser: remove **/
231
+ // these require won't get compiled by to-esm
232
+ this.options.logToFilePath = path.resolve(this.options.logToFile);
233
+ this.logFile = fs.createWriteStream(this.options.logToFilePath, {flags : "a"});
234
+ this.EOL = os.EOL;
235
+ /** to-esm-browser: end-remove **/
218
236
  }
219
237
 
220
-
238
+ /** to-esm-browser: add
221
239
  this.realConsoleLog("LogToFile is not supported in this environment. ")
222
-
240
+ **/
223
241
 
224
242
  }
225
243
 
@@ -360,17 +378,29 @@ class AnaLogger
360
378
  return (context.hasOwnProperty("contextName") && context.hasOwnProperty("target"));
361
379
  }
362
380
 
381
+ setContext(contextName, context)
382
+ {
383
+ this.contexts[contextName] = context;
384
+ }
385
+
386
+ setDefaultContext(context)
387
+ {
388
+ this.setContext(PREDEFINED_CONTEXT_NAMES.DEFAULT, context);
389
+ }
390
+
363
391
  generateDefaultContext()
364
392
  {
365
- const defaultContext = {
366
- name : "DEFAULT",
367
- contextName: "DEFAULT",
368
- target : "ALL",
369
- symbol : "⚡"
370
- };
393
+ let defaultContext = this.contexts[PREDEFINED_CONTEXT_NAMES.DEFAULT] || {};
394
+ defaultContext = Object.assign({},
395
+ {
396
+ name : PREDEFINED_CONTEXT_NAMES.DEFAULT,
397
+ contextName: PREDEFINED_CONTEXT_NAMES.DEFAULT,
398
+ target : "ALL",
399
+ symbol : "⚡",
400
+ color: COLOR_TABLE[1]
401
+ }, defaultContext);
371
402
 
372
403
  defaultContext.id = this.logIndex++;
373
- defaultContext.color = COLOR_TABLE[1];
374
404
  return defaultContext;
375
405
  }
376
406
 
@@ -385,8 +415,10 @@ class AnaLogger
385
415
  generateErrorContext()
386
416
  {
387
417
  const errorContext = this.generateDefaultContext();
418
+ errorContext.name = PREDEFINED_CONTEXT_NAMES.ERROR;
419
+ errorContext.contextName = PREDEFINED_CONTEXT_NAMES.ERROR;
388
420
  errorContext.color = COLOR_TABLE[0];
389
- errorContext.symbol = "v";
421
+ errorContext.symbol = "";
390
422
  errorContext.error = true;
391
423
  return errorContext;
392
424
  }
@@ -424,8 +456,8 @@ class AnaLogger
424
456
  setContexts(contextTable)
425
457
  {
426
458
  const arr = Object.keys(contextTable);
427
- contextTable["DEFAULT"] = this.contexts["DEFAULT"] = this.generateDefaultContext();
428
- contextTable["ERROR"] = this.contexts["ERROR"] = this.generateErrorContext();
459
+ contextTable[PREDEFINED_CONTEXT_NAMES.DEFAULT] = this.contexts[PREDEFINED_CONTEXT_NAMES.DEFAULT] = this.generateDefaultContext();
460
+ contextTable[PREDEFINED_CONTEXT_NAMES.ERROR] = this.contexts[PREDEFINED_CONTEXT_NAMES.ERROR] = this.generateErrorContext();
429
461
  arr.forEach((key) =>
430
462
  {
431
463
  const contextPassed = contextTable[key] || {};
@@ -522,6 +554,19 @@ class AnaLogger
522
554
  this.logFile.write(text + this.EOL);
523
555
  }
524
556
 
557
+ convertArgumentsToText(args)
558
+ {
559
+ let text = "";
560
+ const n = args.length;
561
+ for (let i = 0; i < n; ++i)
562
+ {
563
+ text = stringify(args[i], null, 2);
564
+ text += i < n - 1 ? EOL : "";
565
+ }
566
+
567
+ return text;
568
+ }
569
+
525
570
  /**
526
571
  * Display log following template
527
572
  * @param context
@@ -530,6 +575,8 @@ class AnaLogger
530
575
  {
531
576
  try
532
577
  {
578
+ let message = "";
579
+
533
580
  if (!this.isTargetAllowed(context.target))
534
581
  {
535
582
  return;
@@ -538,10 +585,18 @@ class AnaLogger
538
585
  let args = Array.prototype.slice.call(arguments);
539
586
  args.shift();
540
587
 
541
- const message = args.join(" | ");
588
+ if (context.format === "no")
589
+ {
590
+ message = this.convertArgumentsToText(args);
591
+ }
592
+ else
593
+ {
594
+ // message = args.join(" | ");
595
+ message = this.convertArgumentsToText(args);
596
+ }
542
597
 
543
598
  let output = "";
544
- const text = this.format({...context, message});
599
+ let text = this.format({...context, message});
545
600
 
546
601
  ++this.logCounter;
547
602
 
@@ -552,6 +607,7 @@ class AnaLogger
552
607
  {
553
608
  this.writeLogToDom(context, text);
554
609
  }
610
+
555
611
  output = `%c${text}`;
556
612
  }
557
613
  else
@@ -584,6 +640,11 @@ class AnaLogger
584
640
  this.realConsoleLog(output);
585
641
  }
586
642
 
643
+ if (context.format === "no")
644
+ {
645
+ this.realConsoleLog(args);
646
+ }
647
+
587
648
  this.errorTargetHandler(context, args);
588
649
  }
589
650
  catch (e)
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "analogger",
3
- "version": "1.8.4",
3
+ "version": "1.9.1",
4
4
  "description": "Js Logger",
5
- "main": "./example/cjs/demo.cjs",
6
- "module": "./generated/browser/demo.mjs",
5
+ "main": "./src/cjs/ana-logger.cjs",
6
+ "module": "./generated/browser/ana-logger.mjs",
7
7
  "type": "module",
8
8
  "exports": {
9
9
  ".": {
10
- "require": "./example/cjs/demo.cjs",
11
- "import": "./generated/browser/demo.mjs"
10
+ "require": "./src/cjs/ana-logger.cjs",
11
+ "import": "./generated/browser/ana-logger.mjs"
12
12
  }
13
13
  },
14
14
  "scripts": {
@@ -22,20 +22,24 @@
22
22
  "*** Pre-Cleaning-2 ****": "# Clean directory",
23
23
  "*** Pre-Cleaning-3 ****": "# ----------------------------------------------------------------------------------------------------------",
24
24
  "clean:generated": "rimraf ./generated && rimraf ./dist",
25
+ "clean:generated:terminal": "rimraf ./generated/terminal && rimraf ./dist",
26
+ "clean:generated:browser": "rimraf ./generated/browser && rimraf ./dist",
25
27
  "*** On the Terminal-1 ****": "# ----------------------------------------------------------------------------------------------------------",
26
28
  "*** On the Terminal-2 ****": "# Generate ESM code",
27
29
  "*** On the Terminal-3 ****": "# ----------------------------------------------------------------------------------------------------------",
28
- "build:esm:terminal": "npm run clean:generated && to-esm.cmd example/cjs/demo.cjs --output=generated/terminal/ --entrypoint=./src/cjs/ana-logger.cjs --config=\".toesm.cjs\" --target=esm --update-all",
29
- "demo:terminal:esm": "npm run build:esm:terminal && node ./generated/terminal/demo.mjs",
30
+ "build:esm:terminal": "npm run clean:generated:terminal && to-esm.cmd ./src/cjs/ana-logger.cjs --output generated/terminal/ --config .toesm.cjs --target esm --update-all",
31
+ "build:terminal:esm:demo": "npm run clean:generated:terminal && to-esm.cmd example/cjs/demo.cjs --output=generated/terminal/ --entrypoint=./src/cjs/ana-logger.cjs --config=\".toesm.cjs\" --target=esm --update-all",
32
+ "demo:terminal:esm": "npm run build:terminal:esm:demo && node ./generated/terminal/demo.mjs",
30
33
  "*** In the Browser-1 ****": "# ----------------------------------------------------------------------------------------------------------",
31
34
  "*** In the Browser-2 ****": "# Generate Browser code",
32
35
  "*** In the Browser-3 ****": "# ----------------------------------------------------------------------------------------------------------",
33
- "build:esm:browser": "npm run clean:generated && to-esm.cmd example/cjs/demo.cjs --output=generated/browser/ --entrypoint=./src/cjs/ana-logger.cjs --config=\".toesm.cjs\" --target=browser --update-all --bundle=\"./dist/analogger-browser.min.mjs\"",
34
- "demo:browser": "npm run build:esm:browser && node example/cjs/demo.cjs",
36
+ "build:esm:browser": "npm run clean:generated:browser && to-esm.cmd ./src/cjs/ana-logger.cjs --output generated/browser/ --config .toesm.cjs --target browser --update-all",
37
+ "build:browser:demo": "npm run clean:generated:browser && to-esm.cmd example/cjs/demo.cjs --output generated/browser/ --entrypoint ./src/cjs/ana-logger.cjs --config .toesm.cjs --target browser --bundle ./dist/analogger-browser.min.mjs",
38
+ "demo:browser": "npm run build:browser:demo && node example/cjs/demo.cjs",
35
39
  "*** In the Browser with importmap-1 ****": "# ----------------------------------------------------------------------------------------------------------",
36
40
  "*** In the Browser with importmap-2 ****": "# Generate ESM code with import map",
37
41
  "*** In the Browser with importmap-3 ****": "# ----------------------------------------------------------------------------------------------------------",
38
- "build:browser:importmap": "npm run build:esm:browser -- --html=example/index.html",
42
+ "build:browser:importmap": "npm run build:browser:demo -- --html=example/index.html",
39
43
  "demo:browser:importmap": "npm run build:browser:importmap && node example/cjs/demo.cjs",
40
44
  "quick:run": "node example/cjs/demo.cjs"
41
45
  },
@@ -86,6 +90,7 @@
86
90
  "chalk-cjs": "npm:chalk@^4.1.2",
87
91
  "color-convert": "^2.0.1",
88
92
  "color-convert-cjs": "npm:color-convert@^2.0.1",
93
+ "flatted": "^3.2.5",
89
94
  "js-beautify": "^1.10.1-rc2",
90
95
  "node_modules-path": "^2.0.5",
91
96
  "pretty-js": "^0.2.2",
@@ -7,6 +7,12 @@ const os = require("os");
7
7
  const toAnsi = require("to-ansi");
8
8
  const rgbHex = require("rgb-hex-cjs");
9
9
  const {COLOR_TABLE, SYSTEM} = require("./constants.cjs");
10
+ const PREDEFINED_CONTEXT_NAMES = {
11
+ "DEFAULT": "DEFAULT",
12
+ "ERROR": "ERROR"
13
+ };
14
+
15
+ const {stringify} = require("flatted");
10
16
 
11
17
  const EOL =`
12
18
  `;
@@ -221,7 +227,7 @@ class AnaLogger
221
227
 
222
228
  /** to-esm-browser: add
223
229
  this.realConsoleLog("LogToFile is not supported in this environment. ")
224
- * **/
230
+ **/
225
231
 
226
232
  }
227
233
 
@@ -362,17 +368,29 @@ class AnaLogger
362
368
  return (context.hasOwnProperty("contextName") && context.hasOwnProperty("target"));
363
369
  }
364
370
 
371
+ setContext(contextName, context)
372
+ {
373
+ this.contexts[contextName] = context;
374
+ }
375
+
376
+ setDefaultContext(context)
377
+ {
378
+ this.setContext(PREDEFINED_CONTEXT_NAMES.DEFAULT, context);
379
+ }
380
+
365
381
  generateDefaultContext()
366
382
  {
367
- const defaultContext = {
368
- name : "DEFAULT",
369
- contextName: "DEFAULT",
370
- target : "ALL",
371
- symbol : "⚡"
372
- };
383
+ let defaultContext = this.contexts[PREDEFINED_CONTEXT_NAMES.DEFAULT] || {};
384
+ defaultContext = Object.assign({},
385
+ {
386
+ name : PREDEFINED_CONTEXT_NAMES.DEFAULT,
387
+ contextName: PREDEFINED_CONTEXT_NAMES.DEFAULT,
388
+ target : "ALL",
389
+ symbol : "⚡",
390
+ color: COLOR_TABLE[1]
391
+ }, defaultContext);
373
392
 
374
393
  defaultContext.id = this.logIndex++;
375
- defaultContext.color = COLOR_TABLE[1];
376
394
  return defaultContext;
377
395
  }
378
396
 
@@ -387,8 +405,10 @@ class AnaLogger
387
405
  generateErrorContext()
388
406
  {
389
407
  const errorContext = this.generateDefaultContext();
408
+ errorContext.name = PREDEFINED_CONTEXT_NAMES.ERROR;
409
+ errorContext.contextName = PREDEFINED_CONTEXT_NAMES.ERROR;
390
410
  errorContext.color = COLOR_TABLE[0];
391
- errorContext.symbol = "v";
411
+ errorContext.symbol = "";
392
412
  errorContext.error = true;
393
413
  return errorContext;
394
414
  }
@@ -426,8 +446,8 @@ class AnaLogger
426
446
  setContexts(contextTable)
427
447
  {
428
448
  const arr = Object.keys(contextTable);
429
- contextTable["DEFAULT"] = this.contexts["DEFAULT"] = this.generateDefaultContext();
430
- contextTable["ERROR"] = this.contexts["ERROR"] = this.generateErrorContext();
449
+ contextTable[PREDEFINED_CONTEXT_NAMES.DEFAULT] = this.contexts[PREDEFINED_CONTEXT_NAMES.DEFAULT] = this.generateDefaultContext();
450
+ contextTable[PREDEFINED_CONTEXT_NAMES.ERROR] = this.contexts[PREDEFINED_CONTEXT_NAMES.ERROR] = this.generateErrorContext();
431
451
  arr.forEach((key) =>
432
452
  {
433
453
  const contextPassed = contextTable[key] || {};
@@ -524,6 +544,44 @@ class AnaLogger
524
544
  this.logFile.write(text + this.EOL);
525
545
  }
526
546
 
547
+ convertArgumentsToText(args)
548
+ {
549
+ const strs = [];
550
+ let text;
551
+ const n = args.length;
552
+ for (let i = 0; i < n; ++i)
553
+ {
554
+ let str;
555
+ let arg = args[i];
556
+
557
+ try
558
+ {
559
+ str = JSON.stringify(arg);
560
+ }
561
+ catch (e)
562
+ {
563
+
564
+ }
565
+
566
+ if (!str)
567
+ {
568
+ try
569
+ {
570
+ str = stringify(arg);
571
+ }
572
+ catch (e)
573
+ {
574
+
575
+ }
576
+ }
577
+
578
+ strs.push(str);
579
+ }
580
+
581
+ text = strs.join("•");
582
+ return text;
583
+ }
584
+
527
585
  /**
528
586
  * Display log following template
529
587
  * @param context
@@ -532,6 +590,8 @@ class AnaLogger
532
590
  {
533
591
  try
534
592
  {
593
+ let message = "";
594
+
535
595
  if (!this.isTargetAllowed(context.target))
536
596
  {
537
597
  return;
@@ -540,10 +600,17 @@ class AnaLogger
540
600
  let args = Array.prototype.slice.call(arguments);
541
601
  args.shift();
542
602
 
543
- const message = args.join(" | ");
603
+ // if (context.format === "no")
604
+ // {
605
+ // message = this.convertArgumentsToText(args);
606
+ // }
607
+ // else
608
+ // {
609
+ message = this.convertArgumentsToText(args);
610
+ // }
544
611
 
545
612
  let output = "";
546
- const text = this.format({...context, message});
613
+ let text = this.format({...context, message});
547
614
 
548
615
  ++this.logCounter;
549
616
 
@@ -554,6 +621,7 @@ class AnaLogger
554
621
  {
555
622
  this.writeLogToDom(context, text);
556
623
  }
624
+
557
625
  output = `%c${text}`;
558
626
  }
559
627
  else
@@ -586,6 +654,11 @@ class AnaLogger
586
654
  this.realConsoleLog(output);
587
655
  }
588
656
 
657
+ // if (context.format === "no")
658
+ // {
659
+ // this.realConsoleLog(args);
660
+ // }
661
+
589
662
  this.errorTargetHandler(context, args);
590
663
  }
591
664
  catch (e)
@@ -1,2 +0,0 @@
1
- const s={};{s["691688ee4a625b95e9da121716860eed508244a8d18f0b3c060da20f5fcdad09"]={};const o=["#d2466e","#FFA07A","#FF7F50","#FF6347","#FFE4B5","#ADFF2F","#808000","#40E0D0","#1E90FF","#EE82EE","#708090","#DEB887","#FE642E","#210B61","#088A4B","#5E610B","#FA8258","#088A68","#B40431"],t={BROWSER:"BROWSER",NODE:"NODE"};var r=o,e=t;s["691688ee4a625b95e9da121716860eed508244a8d18f0b3c060da20f5fcdad09"].COLOR_TABLE=r,s["691688ee4a625b95e9da121716860eed508244a8d18f0b3c060da20f5fcdad09"].SYSTEM=e}s["37feee54896c340bb578ce5b0f398fc0c97d65b8575a4553f2e082a496645c80"]={},s["37feee54896c340bb578ce5b0f398fc0c97d65b8575a4553f2e082a496645c80"].default=function(e,o,t,s){var r=(e+(s||"")).toString().includes("%");if("string"==typeof e?[e,o,t,s]=e.match(/(0?\.?\d{1,3})%?\b/g).map(e=>Number(e)):void 0!==s&&(s=Number.parseFloat(s)),"number"!=typeof e||"number"!=typeof o||"number"!=typeof t||255<e||255<o||255<t)throw new TypeError("Expected three numbers below 256");if("number"==typeof s){if(!r&&0<=s&&s<=1)s=Math.round(255*s);else{if(!(r&&0<=s&&s<=100))throw new TypeError(`Expected alpha value (${s}) as a fraction or percentage`);s=Math.round(255*s/100)}s=(256|s).toString(16).slice(1)}else s="";return(t|o<<8|e<<16|1<<24).toString(16).slice(1)+s};{s.f919b6b1b49ea775df278d9a53baeb24cbc3173d1e555db776aa666bbb6cb102={};const i={Foreground:38,Background:48},d="",c={Bold:"",Underline:"",Reversed:""},h=(e,o,t)=>e===o&&o===t?e<8?16:248<e?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(o/255*5)+Math.round(t/255*5),u=e=>{e=e.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,function(e,o,t,s){return o+o+t+t+s+s});e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return e?{red:parseInt(e[1],16),blue:parseInt(e[2],16),green:parseInt(e[3],16)}:{}},p=function(e,o,t){return t<0&&(t+=1),1<t&&--t,t<1/6?e+6*(o-e)*t:t<.5?o:t<2/3?e+(o-e)*(2/3-t)*6:e};function n({red:e,blue:o,green:t},s=!0){if(void 0===e||void 0===o||void 0===t)return"";e=h(e,o,t);return`[${s?i.Foreground:i.Background};5;`+e+"m "}function a(e,o){var{red:e,green:t,blue:s}=u(e);return n({red:e,green:t,blue:s},o)}function l({hue:e,saturation:o,lightness:t},s){var{red:e,green:o,blue:t}=(({hue:e,saturation:o,lightness:t})=>{let s,r,i;return 0===o?s=r=i=t:(o=2*t-(t=t<.5?t*(1+o):t+o-t*o),s=p(o,t,e+1/3),r=p(o,t,e),i=p(o,t,e-1/3)),{red:Math.round(255*s),blue:Math.round(255*i),green:Math.round(255*r)}})({hue:e,saturation:o,lightness:t});return n({red:e,green:o,blue:t},s)}function g(e,{fg:o,bg:t,isUnderline:s=!1,isBold:r=!1,isReversed:i=!1}){let n="";return o&&(n+=o),t&&(n+=t),s&&(n+=c.Underline),r&&(n+=c.Bold),i&&(n+=c.Reversed),n+e+d}s.f919b6b1b49ea775df278d9a53baeb24cbc3173d1e555db776aa666bbb6cb102.default={fromRgb:n,fromHexa:a,fromHsl:l,getTextFromRgb:function(e,{fg:o={},bg:t={},isUnderline:s=!1,isBold:r=!1,isReversed:i=!1}){return g(e,{fg:o=o&&n({...o}),bg:t=t&&n({...t},!1),isUnderline:s,isBold:r,isReversed:i})},getTextFromHsl:function(e,{fg:o="",bg:t="",isUnderline:s=!1,isBold:r=!1,isReversed:i=!1}){return g(e,{fg:o=o&&l({...o}),bg:t=t&&l({...t},!1),isUnderline:s,isBold:r,isReversed:i})},getTextFromHex:function(e,{fg:o="",bg:t="",isUnderline:s=!1,isBold:r=!1,isReversed:i=!1}){return g(e,{fg:o=o&&a(o),bg:t=t&&a(t,!1),isUnderline:s,isBold:r,isReversed:i})},hexToRgb:u,rgbToAnsi256:h,hue2rgb:p,RESET:d,FONT_STYLE:c,STYLE:{Bold:"",Underline:"",Reversed:""}}}{s["4d57d38aa40d107726ae91903137473bc8081bb629cc75d09818e590b4424721"]={};let i=s.f919b6b1b49ea775df278d9a53baeb24cbc3173d1e555db776aa666bbb6cb102.default,t=s["37feee54896c340bb578ce5b0f398fc0c97d65b8575a4553f2e082a496645c80"].default,{COLOR_TABLE:o,SYSTEM:e}=s["691688ee4a625b95e9da121716860eed508244a8d18f0b3c060da20f5fcdad09"];class b{system="";logIndex=0;logCounter=0;contexts=[];targets={};activeTarget=null;indexColor=0;format="";keepLog=!1;logHistory=[];$containers=null;options={hideHookMessage:!1};static ALIGN={LEFT:"LEFT",RIGHT:"RIGHT"};static ENVIRONMENT_TYPE={BROWSER:"BROWSER",NODE:"NODE",OTHER:"OTHER"};originalFormatFunction;constructor(){if(b.Instance)return b.Instance;(b.Instance=this).system="object"==typeof process?e.NODE:e.BROWSER,this.format=this.onBuildLog.bind(this),this.originalFormatFunction=this.format,this.errorTargetHandler=this.onError.bind(this),this.errorUserTargetHandler=this.onErrorForUserTarget.bind(this),this.setOptions(this.options),this.realConsoleLog=console.log,this.realConsoleInfo=console.info,this.realConsoleWarn=console.warn,this.realConsoleError=console.error,this.ALIGN=b.ALIGN,this.ENVIRONMENT_TYPE=b.ENVIRONMENT_TYPE}keepLogHistory(){this.keepLog=!0}releaseLogHistory(){this.keepLog=!1}resetLogHistory(){this.logHistory=[]}getLogHistory(e=!0,o=`
2
- `){const t=JSON.parse(JSON.stringify(this.logHistory.slice(0)));return e?t.join(o):t}isNode(){return this.system===e.NODE}isBrowser(){return!this.isNode()}resetLogger(){this.options={contextLenMax:10,idLenMax:5,lidLenMax:5,symbolLenMax:2,messageLenMax:void 0,hideLog:void 0,hideError:void 0,hideHookMessage:void 0,hidePassingTests:void 0,logToDom:void 0,logToFile:void 0,oneConsolePerContext:void 0,silent:void 0}}resetOptions(){this.options.contextLenMax=10,this.options.idLenMax=5,this.options.lidLenMax=5,this.options.messageLenMax=void 0,this.options.symbolLenMax=60,this.options.hideHookMessage=!1,this.options.hidePassingTests=!1,this.options.hideLog=!1,this.options.hideError=!1,this.options.oneConsolePerContext=!0,this.options.logToDom=void 0,this.options.logToDomlogToFile=void 0,this.options.silent=!1}setOptions({contextLenMax:e=10,idLenMax:o=5,lidLenMax:t=5,symbolLenMax:s=2,messageLenMax:r=void 0,hideLog:i=void 0,hideError:n=void 0,hideHookMessage:a=void 0,hidePassingTests:l=void 0,logToDom:g=void 0,logToFile:d=void 0,oneConsolePerContext:c=void 0,silent:h=void 0}=null){this.options.contextLenMax=e,this.options.idLenMax=o,this.options.lidLenMax=t,this.options.messageLenMax=r,this.options.symbolLenMax=s,void 0!==l&&(this.options.hidePassingTests=!!l),void 0!==a&&(this.options.hideHookMessage=!!a),void 0!==i&&(this.options.hideLog=!!i),void 0!==n&&(this.options.hideError=!!n),void 0!==c&&(this.options.oneConsolePerContext=!!c),void 0!==g&&(this.options.logToDom=g||"#analogger"),void 0!==d&&(this.isBrowser()||(this.options.logToFile=d||"./analogger.log"),this.realConsoleLog("LogToFile is not supported in this environment. ")),void 0!==h&&(this.options.silent=!!h,this.options.hideLog=this.options.silent)}getOptions(){return this.options}truncateMessage(e="",{fit:o=0,align:t=b.ALIGN.LEFT}={}){return e=""+e,o&&e.length>=o+2&&(e=e.substring(0,o-3)+"..."),e=t===b.ALIGN.LEFT?e.padEnd(o," "):e.padStart(o," ")}onBuildLog({contextName:e,message:o="",lid:t="",symbol:s=""}={}){const r=new Date;var i=("0"+r.getHours()).slice(-2)+":"+("0"+r.getMinutes()).slice(-2)+":"+("0"+r.getSeconds()).slice(-2),i=this.truncateMessage(i,{fit:7});return e=this.truncateMessage(e,{fit:this.options.contextLenMax,align:b.ALIGN.RIGHT}),t=this.truncateMessage(t,{fit:this.options.lidLenMax}),void 0!==this.options.messageLenMax&&(o=this.truncateMessage(o,{fit:this.options.messageLenMax})),`[${i}] ${e}: (${t}) ${s=this.truncateMessage(s,{fit:this.options.symbolLenMax})} `+o}onErrorForUserTarget(e,...o){this.errorUserTargetHandler(e,...o)}onError(e,...o){e.target===this.targets.USER&&this.onErrorForUserTarget(e,...o)}onDisplayLog(...e){this.log(...e)}onDisplayError(...e){this.error(...e)}setLogFormat(e){if("function"!=typeof e)return console.error("Invalid parameter for setFormat. It is expecting a function or method."),!1;this.format=e.bind(this)}resetLogFormatter(){this.format=this.originalFormatFunction}setErrorHandler(e){this.errorTargetHandler=e.bind(this)}setErrorHandlerForUserTarget(e){this.errorUserTargetHandler=e.bind(this)}isContextValid(e){return"object"==typeof e&&!Array.isArray(e)&&null!==e&&(e.hasOwnProperty("contextName")&&e.hasOwnProperty("target"))}generateDefaultContext(){const e={name:"DEFAULT",contextName:"DEFAULT",target:"ALL",symbol:"⚡"};return e.id=this.logIndex++,e.color=o[1],e}generateNewContext(){const e=this.generateDefaultContext();return e.color=o[this.indexColor++%(o.length-3)+2],e.symbol="",e}generateErrorContext(){const e=this.generateDefaultContext();return e.color=o[0],e.symbol="v",e.error=!0,e}#allegeProperties(e){let o=e;e=this.generateNewContext();return-1<(o=Object.assign({},e,o)).color.toLowerCase().indexOf("rgb")?o.color="#"+t(o.color):-1===o.color.indexOf("#")&&0,o}setContexts(t){const e=Object.keys(t);t.DEFAULT=this.contexts.DEFAULT=this.generateDefaultContext(),t.ERROR=this.contexts.ERROR=this.generateErrorContext(),e.forEach(e=>{const o=t[e]||{};o.contextName=e,o.name=e,this.contexts[e]=this.#allegeProperties(o),t[e]=this.contexts[e]})}setTargets(e={}){this.targets=Object.assign({},e,{ALL:"ALL",USER:"USER"})}setActiveTarget(e){this.activeTarget=e}isTargetAllowed(e){return!e||!this.activeTarget||(e===this.targets.ALL||this.activeTarget===e)}setColumns(e,o,t){let s=0;for(var r in o)if("name"!==r){var i=o[r];const n=document.createElement("span");n.classList.add("analogger-col","analogger-col-"+r,"analogger-col-"+s),++s,n.textContent=i,e.append(n)}const n=document.createElement("span");n.classList.add("analogger-col","analogger-col-text","analogger-col-"+s),n.textContent=t,e.append(n)}writeLogToDom(t,s){this.$containers=this.$containers||document.querySelectorAll(this.options.logToDom);for(let o=0;o<this.$containers.length;++o){const r=this.$containers[o];let e=r.querySelector(".analogger-view");e||((e=document.createElement("div")).classList.add("analogger-view"),r.append(e));const i=document.createElement("div");i.classList.add("to-esm-line"),i.style.color=t.color,i.setAttribute("data-log-counter",this.logCounter),i.setAttribute("data-log-index",this.logIndex),this.setColumns(i,t,s),e.append(i)}}writeLogToFile(e){this.logFile.write(e+this.EOL)}processOutput(t={}){try{if(!this.isTargetAllowed(t.target))return;let e=Array.prototype.slice.call(arguments);e.shift();var s=e.join(" | ");let o="";var r=this.format({...t,message:s});if(++this.logCounter,this.isBrowser()?(t.environnment=b.ENVIRONMENT_TYPE.BROWSER,this.options.logToDom&&this.writeLogToDom(t,r),o="%c"+r):(t.environnment=b.ENVIRONMENT_TYPE.NODE,o=i.getTextFromHex(r,{fg:t.color}),this.options.logToFile&&this.writeLogToFile(r)),this.keepLog&&this.logHistory.push(o),this.options.hideLog)return;this.isBrowser()?this.realConsoleLog(o,"color: "+t.color):this.realConsoleLog(o),this.errorTargetHandler(t,e)}catch(e){console.error("AnaLogger:",e.message)}}isExtendedOptionsPassed(e){return"object"==typeof e&&(e.hasOwnProperty("context")||e.hasOwnProperty("target")||e.hasOwnProperty("color")||e.hasOwnProperty("lid"))}convertToContext(e,o){o=o||this.generateDefaultContext();let t=e=e||o;if(e.context&&"object"==typeof e.context){const s=Object.assign({},e);delete s.context,t=Object.assign({},e.context,s)}return delete(t=Object.assign({},o,t)).context,t}log(e,...o){if(!this.isExtendedOptionsPassed(e))return t=this.generateDefaultContext(),void this.processOutput.apply(this,[t,e,...o]);var t=this.convertToContext(e);this.processOutput.apply(this,[t,...o])}error(e,...o){if(!this.options.hideError){if(!this.isExtendedOptionsPassed(e))return t=this.generateErrorContext(),void this.processOutput.apply(this,[t,e,...o]);var t=this.generateErrorContext(),t=this.convertToContext(e,t),s=Array.prototype.slice.call(arguments,1);this.log(t,...s)}}overrideError(){this.options.hideHookMessage||this.realConsoleLog("AnaLogger: Hook placed on console.error"),console.error=this.onDisplayError.bind(this)}overrideConsole({log:e=!0,info:o=!0,warn:t=!0,error:s=!1}={}){this.options.hideHookMessage||this.realConsoleLog("AnaLogger: Hook placed on console.log"),e&&(console.log=this.onDisplayLog.bind(this)),o&&(console.info=this.onDisplayLog.bind(this)),t&&(console.warn=this.onDisplayLog.bind(this)),s&&this.overrideError()}removeOverrideError(){console.warn=this.realConsoleError}removeOverride({log:e=!0,info:o=!0,warn:t=!0,error:s=!1}={}){e&&(console.log=this.realConsoleLog),o&&(console.info=this.realConsoleInfo),t&&(console.warn=this.realConsoleWarn),s&&this.removeOverrideError()}info(...e){return this.log(...e)}warn(...e){return this.log(...e)}alert(...e){if(this.isNode())return this.log(...e);e=e.join(" | ");alert(e)}assert(e,o=!0,...t){try{return"function"==typeof e?e(...t)!==o?(this.error("Asset failed"),!1):(this.options.hidePassingTests||this.log("SUCCESS: Assert passed"),!0):e!==o?(this.error("Assert failed"),!1):(this.options.hidePassingTests||this.log("SUCCESS: Assert passed"),!0)}catch(e){this.error("Unexpected error in assert")}return!1}}s["4d57d38aa40d107726ae91903137473bc8081bb629cc75d09818e590b4424721"].default=new b,r=new b,s["4d57d38aa40d107726ae91903137473bc8081bb629cc75d09818e590b4424721"].anaLogger=r}s.c30121e4056ba978b4fb451fa7489c6ff84e611cdca39ae86de3030d10e7073e={},s.c30121e4056ba978b4fb451fa7489c6ff84e611cdca39ae86de3030d10e7073e.LOG_CONTEXTS={STANDARD:{},TEST:{color:"#B18904",symbol:"⏰"},TEST2:{color:"rgb(127, 127, 127)",symbol:"⏰"},TEST3:{color:"blue",symbol:"⏰"},C1:null,C2:null,C3:null,DEFAULT:{}},s.c30121e4056ba978b4fb451fa7489c6ff84e611cdca39ae86de3030d10e7073e.LOG_TARGETS={ALL:"ALL",DEV1:"TOM",DEV2:"TIM",DEV3:"ME",USER:"USER"};{s.ca63110bb9882fce16420271e1c0aa1a22360931c93ababb90ba99d2da8a867c={};var{LOG_CONTEXTS:e,LOG_TARGETS:r}=s.c30121e4056ba978b4fb451fa7489c6ff84e611cdca39ae86de3030d10e7073e;let o=s["4d57d38aa40d107726ae91903137473bc8081bb629cc75d09818e590b4424721"]["anaLogger"];o.keepLogHistory(),o.setContexts(e),o.setTargets(r),o.setActiveTarget(r.DEV3),o.setOptions({logToDom:".analogger"}),o.setOptions({silent:!0}),console.log("=========================="),o.log(e.C1,"You should not see this C1"),o.log(e.C2,"You should not see this C2"),o.log(e.C3,"You should not see this C3"),o.setOptions({silent:!1,hideError:!1,logToFile:"./logme.log"}),o.log(e.C1,"You should see this C100"),o.log(e.C2,"You should see this C200"),o.log(e.C3,"You should see this C300"),console.log("============= From History ==========================="),console.log(o.getLogHistory()),console.log("============= From History (Closed) =================="),o.assert(!0),o.assert(!1),o.assert(()=>!0,!0),o.assert((e,o)=>e===o,!0,2,2),console.log("-------------------------- console.log is about to be overridden"),o.overrideConsole(),console.log("Log After override <= Console.log is overridden"),console.error("-------------------------- console.error is about to be overridden"),o.overrideError(),console.error("Hook on Error placed after override <= Console.error is also overridden"),console.log("=========================="),o.log(e.STANDARD,"Basic Log example 2","+Something 0","+Something 1"),o.log({context:e.TEST,lid:1e5},"Test Log example"),o.log({context:e.TEST,target:r.DEV3,lid:100001},"Test Log example with active target"),o.log({context:e.TEST,target:r.DEV1,lid:100002},"Test Log example with DEV1 target"),o.log({context:e.TEST,target:r.DEV2,lid:100003},"Test Log example with DEV2 target"),o.log("Test Log example with DEFAULT target"),o.log(e.TEST,"Test Log example","+Something 3"),o.log(e.C1,"Test Log example C1"),o.log(e.C2,"Test Log example C2"),o.log(e.C3,"Test Log example C3"),console.log(e.C1,"Test Log example C4"),console.log(e.C1,"Test Log example C5"),console.log(e.C1,"Test Log example C6"),console.error({context:e.ERROR,lid:2e5},"Testing Error 1"),console.error(e.ERROR,"Testing Error 2"),console.error("Testing Error 3"),console.error(void 0,"Testing Error 4"),console.error({context:e.ERROR,target:r.USER,lid:200010},"Testing Error 4"),o.info("Hello from alert",{aaa:1012}),o.setActiveTarget(r.USER),o.setErrorHandlerForUserTarget(function(e){o.log("User explicitly see this message"),o.info("User explicitly see this message",e)}),console.error({context:e.ERROR,target:r.USER,lid:200020},"Testing Error that triggers a special handler"),o.setLogFormat(function({contextName:e,message:o}){return e+": "+o}),console.log(e.C1,"Test Log example C4 with new format"),console.log(e.C1,"Test Log example C5 with new format"),console.log(e.C1,"Test Log example C6 with new format"),o.log("Basic Log example 1")}
@@ -1,102 +0,0 @@
1
- /**
2
- * DO NOT EDIT THIS FILE DIRECTLY.
3
- * This file is generated following the conversion of
4
- * [./example/cjs/demo.cjs]{@link ./example/cjs/demo.cjs}
5
- *
6
- **/
7
- import {LOG_CONTEXTS, LOG_TARGETS} from "./example/cjs/contexts-def.mjs";
8
- import {anaLogger} from "./src/cjs/ana-logger.mjs";
9
-
10
-
11
- anaLogger.keepLogHistory();
12
-
13
- anaLogger.setContexts(LOG_CONTEXTS);
14
- anaLogger.setTargets(LOG_TARGETS);
15
- anaLogger.setActiveTarget(LOG_TARGETS.DEV3);
16
- anaLogger.setOptions({logToDom: ".analogger"});
17
- anaLogger.setOptions({silent: true});
18
-
19
- console.log("==========================");
20
- anaLogger.log(LOG_CONTEXTS.C1, "You should not see this C1");
21
- anaLogger.log(LOG_CONTEXTS.C2, "You should not see this C2");
22
- anaLogger.log(LOG_CONTEXTS.C3, "You should not see this C3");
23
-
24
- anaLogger.setOptions({silent: false, hideError: false, logToFile: "./logme.log"});
25
- anaLogger.log(LOG_CONTEXTS.C1, "You should see this C100");
26
- anaLogger.log(LOG_CONTEXTS.C2, "You should see this C200");
27
- anaLogger.log(LOG_CONTEXTS.C3, "You should see this C300");
28
-
29
- console.log("============= From History ===========================");
30
- console.log(anaLogger.getLogHistory());
31
- console.log("============= From History (Closed) ==================");
32
-
33
- anaLogger.assert(1 === 1);
34
- anaLogger.assert(1 === 2);
35
- anaLogger.assert(() => true, true);
36
-
37
- anaLogger.assert((a, b) => a === b, true, 2, 2);
38
-
39
- console.log("-------------------------- console.log is about to be overridden");
40
- anaLogger.overrideConsole();
41
- console.log("Log After override <= Console.log is overridden");
42
- console.error("-------------------------- console.error is about to be overridden");
43
- anaLogger.overrideError();
44
- console.error("Hook on Error placed after override <= Console.error is also overridden");
45
- console.log("==========================");
46
-
47
- anaLogger.log(LOG_CONTEXTS.STANDARD, "Basic Log example 2", "+Something 0", "+Something 1");
48
-
49
- anaLogger.log({context: LOG_CONTEXTS.TEST, lid: 100000}, "Test Log example");
50
- anaLogger.log({
51
- context: LOG_CONTEXTS.TEST,
52
- target : LOG_TARGETS.DEV3,
53
- lid : 100001
54
- }, "Test Log example with active target");
55
- anaLogger.log({context: LOG_CONTEXTS.TEST, target: LOG_TARGETS.DEV1, lid: 100002}, "Test Log example with DEV1 target");
56
- anaLogger.log({context: LOG_CONTEXTS.TEST, target: LOG_TARGETS.DEV2, lid: 100003}, "Test Log example with DEV2 target");
57
- anaLogger.log("Test Log example with DEFAULT target");
58
-
59
- anaLogger.log(LOG_CONTEXTS.TEST, "Test Log example", "+Something 3");
60
- anaLogger.log(LOG_CONTEXTS.C1, "Test Log example C1");
61
- anaLogger.log(LOG_CONTEXTS.C2, "Test Log example C2");
62
- anaLogger.log(LOG_CONTEXTS.C3, "Test Log example C3");
63
-
64
- console.log(LOG_CONTEXTS.C1, "Test Log example C4");
65
- console.log(LOG_CONTEXTS.C1, "Test Log example C5");
66
- console.log(LOG_CONTEXTS.C1, "Test Log example C6");
67
-
68
- console.error({context: LOG_CONTEXTS.ERROR, lid: 200000}, "Testing Error 1");
69
- console.error(LOG_CONTEXTS.ERROR, "Testing Error 2");
70
- console.error("Testing Error 3");
71
- console.error(undefined, "Testing Error 4");
72
-
73
- console.error({context: LOG_CONTEXTS.ERROR, target: LOG_TARGETS.USER, lid: 200010}, "Testing Error 4");
74
-
75
-
76
- anaLogger.info("Hello from alert", {aaa: 1012});
77
-
78
- anaLogger.setActiveTarget(LOG_TARGETS.USER);
79
- anaLogger.setErrorHandlerForUserTarget(function (context/*, ...args*/)
80
- {
81
- anaLogger.log("User explicitly see this message");
82
- anaLogger.info("User explicitly see this message", context);
83
- });
84
-
85
- console.error({
86
- context: LOG_CONTEXTS.ERROR,
87
- target : LOG_TARGETS.USER,
88
- lid : 200020
89
- }, "Testing Error that triggers a special handler");
90
-
91
- anaLogger.setLogFormat(
92
- function({contextName, message})
93
- {
94
- return `${contextName}: ${message}`;
95
- }
96
- );
97
-
98
- console.log(LOG_CONTEXTS.C1, "Test Log example C4 with new format");
99
- console.log(LOG_CONTEXTS.C1, "Test Log example C5 with new format");
100
- console.log(LOG_CONTEXTS.C1, "Test Log example C6 with new format");
101
-
102
- anaLogger.log("Basic Log example 1");
@@ -1,22 +0,0 @@
1
- /**
2
- * DO NOT EDIT THIS FILE DIRECTLY.
3
- * This file is generated following the conversion of
4
- * [./example/cjs/contexts-def.cjs]{@link ./example/cjs/contexts-def.cjs}
5
- *
6
- **/
7
- /**
8
- *
9
- * @type {{C3: null, TEST: {symbol: string, color: string}, STANDARD: {}, C1: null, DEFAULT: {}, C2: null}}
10
- */
11
- export const LOG_CONTEXTS = {
12
- STANDARD: {},
13
- TEST: {color: "#B18904", symbol: "⏰"},
14
- TEST2: {color: "rgb(127, 127, 127)", symbol: "⏰"},
15
- TEST3: {color: "blue", symbol: "⏰"},
16
- C1: null,
17
- C2: null,
18
- C3: null,
19
- DEFAULT: {}
20
- };
21
-
22
- export const LOG_TARGETS = {ALL: "ALL", DEV1: "TOM", DEV2: "TIM", DEV3: "ME", USER: "USER"};
@@ -1,43 +0,0 @@
1
- /**
2
- * DO NOT EDIT THIS FILE DIRECTLY.
3
- * This file is generated following the conversion of
4
- * [./node_modules/rgb-hex/index.js]{@link ./node_modules/rgb-hex/index.js}
5
- *
6
- **/
7
- export default function rgbHex(red, green, blue, alpha) {
8
- const isPercent = (red + (alpha || '')).toString().includes('%');
9
-
10
- if (typeof red === 'string') {
11
- [red, green, blue, alpha] = red.match(/(0?\.?\d{1,3})%?\b/g).map(component => Number(component));
12
- } else if (alpha !== undefined) {
13
- alpha = Number.parseFloat(alpha);
14
- }
15
-
16
- if (typeof red !== 'number' ||
17
- typeof green !== 'number' ||
18
- typeof blue !== 'number' ||
19
- red > 255 ||
20
- green > 255 ||
21
- blue > 255
22
- ) {
23
- throw new TypeError('Expected three numbers below 256');
24
- }
25
-
26
- if (typeof alpha === 'number') {
27
- if (!isPercent && alpha >= 0 && alpha <= 1) {
28
- alpha = Math.round(255 * alpha);
29
- } else if (isPercent && alpha >= 0 && alpha <= 100) {
30
- alpha = Math.round(255 * alpha / 100);
31
- } else {
32
- throw new TypeError(`Expected alpha value (${alpha}) as a fraction or percentage`);
33
- }
34
-
35
- alpha = (alpha | 1 << 8).toString(16).slice(1); // eslint-disable-line no-mixed-operators
36
- } else {
37
- alpha = '';
38
- }
39
-
40
- // TODO: Remove this ignore comment.
41
- // eslint-disable-next-line no-mixed-operators
42
- return ((blue | green << 8 | red << 16) | 1 << 24).toString(16).slice(1) + alpha;
43
- }
@@ -1,285 +0,0 @@
1
- /**
2
- * DO NOT EDIT THIS FILE DIRECTLY.
3
- * This file is generated following the conversion of
4
- * [./node_modules/to-ansi/index.mjs]{@link ./node_modules/to-ansi/index.mjs}
5
- *
6
- **/
7
- /**
8
- * DO NOT EDIT THIS FILE DIRECTLY.
9
- * This file is generated following the conversion of
10
- * [./index.cjs]{@link ./index.cjs}
11
- *
12
- **/
13
- const COLOR_TYPE = {
14
- Foreground: 38,
15
- Background: 48,
16
- };
17
-
18
- export const RESET = "\x1b[0m";
19
-
20
- export const FONT_STYLE = {
21
- Bold : "\x1b[1m",
22
- Underline: "\x1b[4m",
23
- Reversed : "\x1b[7m",
24
- }
25
-
26
- export const STYLE = {
27
- Bold : "\x1b[1m",
28
- Underline: "\x1b[4m",
29
- Reversed : "\x1b[7m",
30
- }
31
-
32
- /**
33
- * @see [Code and original author]
34
- * {@link https://stackoverflow.com/questions/15682537/ansi-color-specific-rgb-sequence-bash}
35
- * @param red
36
- * @param green
37
- * @param blue
38
- * @returns {number}
39
- */
40
- export const rgbToAnsi256 = (red, green, blue) =>
41
- {
42
- if (red === green && green === blue)
43
- {
44
- if (red < 8)
45
- {
46
- return 16;
47
- }
48
-
49
- if (red > 248)
50
- {
51
- return 231;
52
- }
53
-
54
- return Math.round(((red - 8) / 247) * 24) + 232;
55
- }
56
-
57
- return 16
58
- + (36 * Math.round(red / 255 * 5))
59
- + (6 * Math.round(green / 255 * 5))
60
- + Math.round(blue / 255 * 5);
61
- };
62
-
63
- /**
64
- * @see [Code and original author]
65
- * {@link https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb/5624139#5624139}
66
- * @param hex
67
- * @returns {{red: number, green: number, blue: number}|null}
68
- */
69
- export const hexToRgb = (hex) =>
70
- {
71
- const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
72
- hex = hex.replace(shorthandRegex, function (m, r, g, b)
73
- {
74
- return r + r + g + g + b + b;
75
- });
76
-
77
- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
78
- return result ? {
79
- red : parseInt(result[1], 16),
80
- blue : parseInt(result[2], 16),
81
- green: parseInt(result[3], 16)
82
- } : {};
83
- };
84
-
85
- export const hue2rgb = function hue2rgb(p, q, t)
86
- {
87
- if (t < 0)
88
- {
89
- t += 1;
90
- }
91
- if (t > 1)
92
- {
93
- t -= 1;
94
- }
95
- if (t < 1 / 6)
96
- {
97
- return p + (q - p) * 6 * t;
98
- }
99
- if (t < 1 / 2)
100
- {
101
- return q;
102
- }
103
- if (t < 2 / 3)
104
- {
105
- return p + (q - p) * (2 / 3 - t) * 6;
106
- }
107
- return p;
108
- };
109
-
110
- /**
111
- * Converts an HSL color value to RGB. Conversion formula
112
- * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
113
- * Assumes h, s, and l are contained in the set [0, 1] and
114
- * returns r, g, and b in the set [0, 255].
115
- * @see [Original code and author] {@link https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion}
116
- *
117
- * @param {number} hue The hue
118
- * @param {number} saturation The saturation
119
- * @param {number} lightness The lightness
120
- * @return {Array} The RGB representation
121
- */
122
- const hslToRgb = ({hue, saturation, lightness}) =>
123
- {
124
- let r, g, b;
125
-
126
- if (saturation === 0)
127
- {
128
- r = g = b = lightness; // achromatic
129
- }
130
- else
131
- {
132
- const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
133
- const p = 2 * lightness - q;
134
- r = hue2rgb(p, q, hue + 1 / 3);
135
- g = hue2rgb(p, q, hue);
136
- b = hue2rgb(p, q, hue - 1 / 3);
137
- }
138
-
139
- return {
140
- red : Math.round(r * 255),
141
- blue : Math.round(b * 255),
142
- green: Math.round(g * 255)
143
- };
144
- };
145
-
146
- export function fromRgb ({red, blue, green}, isForeground = true)
147
- {
148
- if (red === undefined || blue === undefined || green === undefined)
149
- {
150
- return "";
151
- }
152
-
153
- const code = rgbToAnsi256(red, blue, green);
154
-
155
- let ground = isForeground ? COLOR_TYPE.Foreground : COLOR_TYPE.Background;
156
- return `\x1b[${ground};5;` + code + "m ";
157
- }
158
-
159
- export function fromHexa (hexa, isForeground)
160
- {
161
- const {red, green, blue} = hexToRgb(hexa);
162
- return fromRgb({red, green, blue}, isForeground);
163
- }
164
-
165
- export function fromHsl ({hue, saturation, lightness}, isForeground)
166
- {
167
- const {red, green, blue} = hslToRgb({hue, saturation, lightness});
168
- return fromRgb({red, green, blue}, isForeground);
169
- }
170
-
171
- function getTextFromAnsi(text, {
172
- fg,
173
- bg,
174
- isUnderline = false,
175
- isBold = false,
176
- isReversed = false
177
- })
178
- {
179
- let prefix = ""
180
- if (fg)
181
- {
182
- prefix = prefix + fg;
183
- }
184
-
185
- if (bg)
186
- {
187
- prefix = prefix + bg;
188
- }
189
-
190
- if (isUnderline)
191
- {
192
- prefix = prefix + FONT_STYLE.Underline;
193
- }
194
-
195
- if (isBold)
196
- {
197
- prefix = prefix + FONT_STYLE.Bold;
198
- }
199
-
200
- if (isReversed)
201
- {
202
- prefix = prefix + FONT_STYLE.Reversed;
203
- }
204
-
205
- return prefix + text + RESET;
206
- }
207
-
208
-
209
- export function getTextFromRgb (text, {
210
- fg = {},
211
- bg = {},
212
- isUnderline = false,
213
- isBold = false,
214
- isReversed = false
215
- })
216
- {
217
- if (fg)
218
- {
219
- fg = fromRgb({...fg});
220
- }
221
-
222
- if (bg)
223
- {
224
- bg = fromRgb({...bg}, false);
225
- }
226
-
227
- return getTextFromAnsi(text,{fg, bg, isUnderline, isBold, isReversed});
228
- }
229
-
230
- export function getTextFromHsl (text, {
231
- fg = "",
232
- bg = "",
233
- isUnderline = false,
234
- isBold = false,
235
- isReversed = false
236
- })
237
- {
238
- if (fg)
239
- {
240
- fg = fromHsl({...fg});
241
- }
242
-
243
- if (bg)
244
- {
245
- bg = fromHsl({...bg}, false);
246
- }
247
-
248
- return getTextFromAnsi(text,{fg, bg, isUnderline, isBold, isReversed});
249
- }
250
-
251
- export function getTextFromHex (text, {
252
- fg = "",
253
- bg = "",
254
- isUnderline = false,
255
- isBold = false,
256
- isReversed = false
257
- })
258
- {
259
- if (fg)
260
- {
261
- fg = fromHexa(fg);
262
- }
263
-
264
- if (bg)
265
- {
266
- bg = fromHexa(bg, false);
267
- }
268
-
269
- return getTextFromAnsi(text,{fg, bg, isUnderline, isBold, isReversed});
270
- }
271
-
272
- export default {
273
- fromRgb, fromHexa, fromHsl, getTextFromRgb, getTextFromHsl, getTextFromHex,
274
- hexToRgb, rgbToAnsi256, hue2rgb, RESET, FONT_STYLE, STYLE
275
- }
276
-
277
-
278
- /**
279
- * For the conversion with to-esm, the named export and the function to export must use the same identifier.
280
- * Otherwise, the conversion will fail.
281
- */
282
-
283
-
284
-
285
-
@@ -1,37 +0,0 @@
1
- /**
2
- * DO NOT EDIT THIS FILE DIRECTLY.
3
- * This file is generated following the conversion of
4
- * [./src/cjs/constants.cjs]{@link ./src/cjs/constants.cjs}
5
- *
6
- **/
7
- const constants = {
8
- COLOR_TABLE: [
9
- "#d2466e", // Error context color
10
- "#FFA07A", // Default context color
11
- "#FF7F50",
12
- "#FF6347",
13
- "#FFE4B5",
14
- "#ADFF2F",
15
- "#808000",
16
- "#40E0D0",
17
- "#1E90FF",
18
- "#EE82EE",
19
- "#708090",
20
- "#DEB887",
21
- "#FE642E",
22
- "#210B61",
23
- "#088A4B",
24
- "#5E610B",
25
- "#FA8258",
26
- "#088A68",
27
- "#B40431",
28
- ],
29
- SYSTEM: {
30
- BROWSER: "BROWSER",
31
- NODE: "NODE"
32
- }
33
-
34
- };
35
-
36
- export const COLOR_TABLE = constants.COLOR_TABLE;
37
- export const SYSTEM = constants.SYSTEM;