@jsenv/humanize 1.5.2 → 1.7.0

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.
Files changed (90) hide show
  1. package/dist/browser/jsenv_humanize_browser.js +539 -482
  2. package/dist/browser/jsenv_humanize_browser.js.map +76 -0
  3. package/dist/node/jsenv_humanize_node.js +58 -7
  4. package/dist/node/jsenv_humanize_node.js.map +97 -0
  5. package/dist/node/jsenv_humanize_node_modules.js +23 -15
  6. package/dist/node/jsenv_humanize_node_modules.js.map +21 -0
  7. package/package.json +20 -17
  8. package/src/_tests/byte/file_size.test.js +0 -18
  9. package/src/_tests/byte/memory.test.js +0 -11
  10. package/src/_tests/content_frame/content_frame.test.js +0 -156
  11. package/src/_tests/content_frame/snapshots/10_line_and_column_are_zero.txt +0 -2
  12. package/src/_tests/content_frame/snapshots/11_line_is_last.txt +0 -3
  13. package/src/_tests/content_frame/snapshots/1_basic.txt +0 -4
  14. package/src/_tests/content_frame/snapshots/2_basic_2.txt +0 -6
  15. package/src/_tests/content_frame/snapshots/3_empty_last_line.txt +0 -7
  16. package/src/_tests/content_frame/snapshots/4_no_column.txt +0 -3
  17. package/src/_tests/content_frame/snapshots/5_line_1_and_2_digits.txt +0 -3
  18. package/src/_tests/content_frame/snapshots/6_line_too_long_column_undefined.txt +0 -3
  19. package/src/_tests/content_frame/snapshots/7_line_too_long_column_near_start.txt +0 -4
  20. package/src/_tests/content_frame/snapshots/8_line_too_long_column_near_middle.txt +0 -4
  21. package/src/_tests/content_frame/snapshots/9_line_too_long_column_near_end.txt +0 -4
  22. package/src/_tests/js_value/_inspect.test.html +0 -22
  23. package/src/_tests/js_value/array.test.js +0 -72
  24. package/src/_tests/js_value/biginit.test.js +0 -35
  25. package/src/_tests/js_value/boolean.test.js +0 -45
  26. package/src/_tests/js_value/date.test.js +0 -15
  27. package/src/_tests/js_value/error.test.js +0 -33
  28. package/src/_tests/js_value/function.test.js +0 -51
  29. package/src/_tests/js_value/instance.test.js +0 -12
  30. package/src/_tests/js_value/null.test.js +0 -6
  31. package/src/_tests/js_value/number.test.js +0 -182
  32. package/src/_tests/js_value/object.test.js +0 -173
  33. package/src/_tests/js_value/regexp.test.js +0 -15
  34. package/src/_tests/js_value/string.test.js +0 -106
  35. package/src/_tests/js_value/symbol.test.js +0 -20
  36. package/src/_tests/js_value/undefined.test.js +0 -6
  37. package/src/_tests/log/log_long.test_manual.mjs +0 -39
  38. package/src/_tests/log/log_modified.test_manual.mjs +0 -7
  39. package/src/_tests/log/logger.test.mjs +0 -90
  40. package/src/_tests/log/spinner.duration.test_manual.mjs +0 -25
  41. package/src/_tests/log/spinner.test.mjs +0 -33
  42. package/src/_tests/log/spinner.test_manual.mjs +0 -15
  43. package/src/_tests/percentage/percentage_distribution.test.mjs +0 -89
  44. package/src/_tests/time/decimals.test.js +0 -119
  45. package/src/_tests/time/duration.test.js +0 -20
  46. package/src/_tests/time/ellapsed.test.js +0 -10
  47. package/src/ansi/ansi_browser.js +0 -3
  48. package/src/ansi/ansi_node.js +0 -13
  49. package/src/ansi/ansi_runtime_agnostic.js +0 -107
  50. package/src/byte/byte.js +0 -44
  51. package/src/content_frame/content_frame.js +0 -157
  52. package/src/error/error_to_html.js +0 -22
  53. package/src/error/error_to_markdown.js +0 -14
  54. package/src/js_value/array.js +0 -58
  55. package/src/js_value/bigint.js +0 -3
  56. package/src/js_value/bigint_object.js +0 -5
  57. package/src/js_value/boolean.js +0 -1
  58. package/src/js_value/boolean_object.js +0 -12
  59. package/src/js_value/constructor.js +0 -10
  60. package/src/js_value/date.js +0 -8
  61. package/src/js_value/error.js +0 -34
  62. package/src/js_value/function.js +0 -20
  63. package/src/js_value/humanize.js +0 -142
  64. package/src/js_value/null.js +0 -1
  65. package/src/js_value/number.js +0 -101
  66. package/src/js_value/number_object.js +0 -9
  67. package/src/js_value/object.js +0 -78
  68. package/src/js_value/regexp.js +0 -1
  69. package/src/js_value/string.js +0 -141
  70. package/src/js_value/string_object.js +0 -10
  71. package/src/js_value/symbol.js +0 -24
  72. package/src/js_value/undefined.js +0 -1
  73. package/src/log/LOG_LEVELS.js +0 -9
  74. package/src/log/call_orderer.js +0 -39
  75. package/src/log/detailed_message.js +0 -29
  76. package/src/log/details.js +0 -26
  77. package/src/log/dynamic_log.js +0 -186
  78. package/src/log/logger.js +0 -85
  79. package/src/log/section.js +0 -50
  80. package/src/log/spinner.js +0 -72
  81. package/src/log/task_log.js +0 -49
  82. package/src/main_browser.js +0 -13
  83. package/src/main_node.js +0 -24
  84. package/src/percentage/distribute_percentages.js +0 -53
  85. package/src/time/time.js +0 -151
  86. package/src/unicode/unicode_browser.js +0 -7
  87. package/src/unicode/unicode_node.js +0 -8
  88. package/src/unicode/unicode_runtime_agnostic.js +0 -56
  89. package/src/utils/decimals.js +0 -95
  90. package/src/utils/indentation.js +0 -38
@@ -1,101 +0,0 @@
1
- // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/rules/numeric-separators-style.js
2
-
3
- export const inspectNumber = (value, { numericSeparator }) => {
4
- if (isNegativeZero(value)) {
5
- return "-0";
6
- }
7
- // isNaN
8
- // eslint-disable-next-line no-self-compare
9
- if (value !== value) {
10
- return "NaN";
11
- }
12
- if (value === Infinity) {
13
- return "Infinity";
14
- }
15
- if (value === -Infinity) {
16
- return "-Infinity";
17
- }
18
- const numberString = String(value);
19
- if (!numericSeparator) {
20
- return numberString;
21
- }
22
- const {
23
- number,
24
- mark = "",
25
- sign = "",
26
- power = "",
27
- } = numberString.match(
28
- /^(?<number>.*?)(?:(?<mark>e)(?<sign>[+-])?(?<power>\d+))?$/i,
29
- ).groups;
30
- const numberWithSeparators = formatNumber(number);
31
- const powerWithSeparators = addSeparator(power, {
32
- minimumDigits: 5,
33
- groupLength: 3,
34
- });
35
- return `${numberWithSeparators}${mark}${sign}${powerWithSeparators}`;
36
- };
37
-
38
- // Use this and instead of Object.is(value, -0)
39
- // because in some corner cases firefox returns false
40
- // for Object.is(-0, -0)
41
- const isNegativeZero = (value) => {
42
- return value === 0 && 1 / value === -Infinity;
43
- };
44
-
45
- const formatNumber = (numberString) => {
46
- const parts = numberString.split(".");
47
- const [integer, fractional] = parts;
48
-
49
- if (parts.length === 2) {
50
- const integerWithSeparators = addSeparator(integer, {
51
- minimumDigits: 5,
52
- groupLength: 3,
53
- });
54
- return `${integerWithSeparators}.${fractional}`;
55
- }
56
-
57
- return addSeparator(integer, {
58
- minimumDigits: 5,
59
- groupLength: 3,
60
- });
61
- };
62
-
63
- const addSeparator = (numberString, { minimumDigits, groupLength }) => {
64
- if (numberString[0] === "-") {
65
- return `-${groupDigits(numberString.slice(1), {
66
- minimumDigits,
67
- groupLength,
68
- })}`;
69
- }
70
- return groupDigits(numberString, { minimumDigits, groupLength });
71
- };
72
-
73
- const groupDigits = (digits, { minimumDigits, groupLength }) => {
74
- const digitCount = digits.length;
75
- if (digitCount < minimumDigits) {
76
- return digits;
77
- }
78
-
79
- let digitsWithSeparator = digits.slice(-groupLength);
80
- let remainingDigits = digits.slice(0, -groupLength);
81
- while (remainingDigits.length) {
82
- const group = remainingDigits.slice(-groupLength);
83
- remainingDigits = remainingDigits.slice(0, -groupLength);
84
- digitsWithSeparator = `${group}_${digitsWithSeparator}`;
85
- }
86
- return digitsWithSeparator;
87
- };
88
-
89
- // const addSeparatorFromLeft = (value, { minimumDigits, groupLength }) => {
90
- // const { length } = value;
91
- // if (length < minimumDigits) {
92
- // return value;
93
- // }
94
-
95
- // const parts = [];
96
- // for (let start = 0; start < length; start += groupLength) {
97
- // const end = Math.min(start + groupLength, length);
98
- // parts.push(value.slice(start, end));
99
- // }
100
- // return parts.join("_");
101
- // };
@@ -1,9 +0,0 @@
1
- import { inspectConstructor } from "./constructor.js";
2
-
3
- export const inspectNumberObject = (
4
- value,
5
- { nestedHumanize, useNew, parenthesis },
6
- ) => {
7
- const numberSource = nestedHumanize(value.valueOf());
8
- return inspectConstructor(`Number(${numberSource})`, { useNew, parenthesis });
9
- };
@@ -1,78 +0,0 @@
1
- import {
2
- preNewLineAndIndentation,
3
- wrapNewLineAndIndentation,
4
- } from "../utils/indentation.js";
5
- import { inspectConstructor } from "./constructor.js";
6
-
7
- export const inspectObject = (
8
- value,
9
- {
10
- nestedHumanize,
11
- seen = [],
12
- depth,
13
- indentUsingTab,
14
- indentSize,
15
- objectConstructor,
16
- parenthesis,
17
- useNew,
18
- },
19
- ) => {
20
- if (seen.indexOf(value) > -1) return "Symbol.for('circular')";
21
-
22
- seen.push(value);
23
-
24
- const propertySourceArray = [];
25
- Object.getOwnPropertyNames(value).forEach((propertyName) => {
26
- const propertyNameAsNumber = parseInt(propertyName, 10);
27
- const propertyNameSource = nestedHumanize(
28
- Number.isInteger(propertyNameAsNumber)
29
- ? propertyNameAsNumber
30
- : propertyName,
31
- );
32
- propertySourceArray.push({
33
- nameOrSymbolSource: propertyNameSource,
34
- valueSource: nestedHumanize(value[propertyName], { seen }),
35
- });
36
- });
37
- Object.getOwnPropertySymbols(value).forEach((symbol) => {
38
- propertySourceArray.push({
39
- nameOrSymbolSource: `[${nestedHumanize(symbol)}]`,
40
- valueSource: nestedHumanize(value[symbol], { seen }),
41
- });
42
- });
43
-
44
- let propertiesSource = "";
45
- propertySourceArray.forEach(({ nameOrSymbolSource, valueSource }, index) => {
46
- if (index === 0) {
47
- propertiesSource += `${nameOrSymbolSource}: ${valueSource}`;
48
- } else {
49
- propertiesSource += `,${preNewLineAndIndentation(
50
- `${nameOrSymbolSource}: ${valueSource}`,
51
- {
52
- depth,
53
- indentUsingTab,
54
- indentSize,
55
- },
56
- )}`;
57
- }
58
- });
59
-
60
- let objectSource;
61
- if (propertiesSource.length) {
62
- objectSource = `${wrapNewLineAndIndentation(propertiesSource, {
63
- depth,
64
- indentUsingTab,
65
- indentSize,
66
- })}`;
67
- } else {
68
- objectSource = "";
69
- }
70
-
71
- if (objectConstructor) {
72
- objectSource = `Object({${objectSource}})`;
73
- } else {
74
- objectSource = `{${objectSource}}`;
75
- }
76
-
77
- return inspectConstructor(objectSource, { parenthesis, useNew });
78
- };
@@ -1 +0,0 @@
1
- export const inspectRegExp = (value) => value.toString();
@@ -1,141 +0,0 @@
1
- const DOUBLE_QUOTE = `"`;
2
- const SINGLE_QUOTE = `'`;
3
- const BACKTICK = "`";
4
-
5
- export const inspectString = (
6
- value,
7
- {
8
- quote = "auto",
9
- canUseTemplateString = false,
10
- preserveLineBreaks = false,
11
- quoteDefault = DOUBLE_QUOTE,
12
- } = {},
13
- ) => {
14
- quote =
15
- quote === "auto"
16
- ? determineQuote(value, { canUseTemplateString, quoteDefault })
17
- : quote;
18
- if (quote === BACKTICK) {
19
- return `\`${escapeTemplateStringSpecialCharacters(value)}\``;
20
- }
21
- return surroundStringWith(value, { quote, preserveLineBreaks });
22
- };
23
-
24
- // https://github.com/mgenware/string-to-template-literal/blob/main/src/main.ts#L1
25
- const escapeTemplateStringSpecialCharacters = (string) => {
26
- string = String(string);
27
- let i = 0;
28
- let escapedString = "";
29
- while (i < string.length) {
30
- const char = string[i];
31
- i++;
32
- escapedString += isTemplateStringSpecialChar(char) ? `\\${char}` : char;
33
- }
34
- return escapedString;
35
- };
36
-
37
- const isTemplateStringSpecialChar = (char) =>
38
- templateStringSpecialChars.indexOf(char) > -1;
39
- const templateStringSpecialChars = ["\\", "`", "$"];
40
-
41
- export const determineQuote = (
42
- string,
43
- { canUseTemplateString, quoteDefault = DOUBLE_QUOTE } = {},
44
- ) => {
45
- const containsDoubleQuote = string.includes(DOUBLE_QUOTE);
46
- if (!containsDoubleQuote) {
47
- return DOUBLE_QUOTE;
48
- }
49
- const containsSimpleQuote = string.includes(SINGLE_QUOTE);
50
- if (!containsSimpleQuote) {
51
- return SINGLE_QUOTE;
52
- }
53
- if (canUseTemplateString) {
54
- const containsBackTick = string.includes(BACKTICK);
55
- if (!containsBackTick) {
56
- return BACKTICK;
57
- }
58
- }
59
- const doubleQuoteCount = string.split(DOUBLE_QUOTE).length - 1;
60
- const singleQuoteCount = string.split(SINGLE_QUOTE).length - 1;
61
- if (singleQuoteCount > doubleQuoteCount) {
62
- return DOUBLE_QUOTE;
63
- }
64
- if (doubleQuoteCount > singleQuoteCount) {
65
- return SINGLE_QUOTE;
66
- }
67
- return quoteDefault;
68
- };
69
-
70
- const inspectChar = (char, { quote, preserveLineBreaks }) => {
71
- const point = char.charCodeAt(0);
72
- if (preserveLineBreaks && (char === "\n" || char === "\r")) {
73
- return char;
74
- }
75
- if (
76
- char === quote ||
77
- point === 92 ||
78
- point < 32 ||
79
- (point > 126 && point < 160) ||
80
- // line separators
81
- point === 8232 ||
82
- point === 8233
83
- ) {
84
- const replacement =
85
- char === quote
86
- ? `\\${quote}`
87
- : point === 8232
88
- ? "\\u2028"
89
- : point === 8233
90
- ? "\\u2029"
91
- : meta[point];
92
- return replacement;
93
- }
94
- return char;
95
- };
96
-
97
- // https://github.com/jsenv/jsenv-uneval/blob/6c97ef9d8f2e9425a66f2c88347e0a118d427f3a/src/internal/escapeString.js#L3
98
- // https://github.com/jsenv/jsenv-inspect/blob/bb11de3adf262b68f71ed82b0a37d4528dd42229/src/internal/string.js#L3
99
- // https://github.com/joliss/js-string-escape/blob/master/index.js
100
- // http://javascript.crockford.com/remedial.html
101
- const surroundStringWith = (string, { quote, preserveLineBreaks }) => {
102
- let result = "";
103
- let last = 0;
104
- const lastIndex = string.length;
105
- let i = 0;
106
- while (i < lastIndex) {
107
- const char = string[i];
108
- const replacement = inspectChar(char, { quote, preserveLineBreaks });
109
- if (char !== replacement) {
110
- if (last === i) {
111
- result += replacement;
112
- } else {
113
- result += `${string.slice(last, i)}${replacement}`;
114
- }
115
- last = i + 1;
116
- }
117
- i++;
118
- }
119
- if (last !== lastIndex) {
120
- result += string.slice(last);
121
- }
122
- return `${quote}${result}${quote}`;
123
- };
124
-
125
- // prettier-ignore
126
- const meta = [
127
- '\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07', // x07
128
- '\\b', '\\t', '\\n', '\\x0B', '\\f', '\\r', '\\x0E', '\\x0F', // x0F
129
- '\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17', // x17
130
- '\\x18', '\\x19', '\\x1A', '\\x1B', '\\x1C', '\\x1D', '\\x1E', '\\x1F', // x1F
131
- '', '', '', '', '', '', '', "\\'", '', '', '', '', '', '', '', '', // x2F
132
- '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x3F
133
- '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x4F
134
- '', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', // x5F
135
- '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x6F
136
- '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\x7F', // x7F
137
- '\\x80', '\\x81', '\\x82', '\\x83', '\\x84', '\\x85', '\\x86', '\\x87', // x87
138
- '\\x88', '\\x89', '\\x8A', '\\x8B', '\\x8C', '\\x8D', '\\x8E', '\\x8F', // x8F
139
- '\\x90', '\\x91', '\\x92', '\\x93', '\\x94', '\\x95', '\\x96', '\\x97', // x97
140
- '\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F', // x9F
141
- ];
@@ -1,10 +0,0 @@
1
- import { inspectConstructor } from "./constructor.js";
2
-
3
- export const inspectStringObject = (
4
- value,
5
- { nestedHumanize, useNew, parenthesis },
6
- ) => {
7
- const stringSource = nestedHumanize(value.valueOf());
8
-
9
- return inspectConstructor(`String(${stringSource})`, { useNew, parenthesis });
10
- };
@@ -1,24 +0,0 @@
1
- export const inspectSymbol = (value, { nestedHumanize, parenthesis }) => {
2
- const symbolDescription = symbolToDescription(value);
3
- const symbolDescriptionSource = symbolDescription
4
- ? nestedHumanize(symbolDescription)
5
- : "";
6
- const symbolSource = `Symbol(${symbolDescriptionSource})`;
7
-
8
- if (parenthesis) return `${symbolSource}`;
9
- return symbolSource;
10
- };
11
-
12
- const symbolToDescription =
13
- "description" in Symbol.prototype
14
- ? (symbol) => symbol.description
15
- : (symbol) => {
16
- const toStringResult = symbol.toString();
17
- const openingParenthesisIndex = toStringResult.indexOf("(");
18
- const closingParenthesisIndex = toStringResult.indexOf(")");
19
- const symbolDescription = toStringResult.slice(
20
- openingParenthesisIndex + 1,
21
- closingParenthesisIndex,
22
- );
23
- return symbolDescription;
24
- };
@@ -1 +0,0 @@
1
- export const inspectUndefined = () => "undefined";
@@ -1,9 +0,0 @@
1
- export const LOG_LEVEL_OFF = "off";
2
-
3
- export const LOG_LEVEL_DEBUG = "debug";
4
-
5
- export const LOG_LEVEL_INFO = "info";
6
-
7
- export const LOG_LEVEL_WARN = "warn";
8
-
9
- export const LOG_LEVEL_ERROR = "error";
@@ -1,39 +0,0 @@
1
- export const createCallOrderer = () => {
2
- const queue = [];
3
- const callWhenPreviousExecutionAreDone = (executionIndex, callback) => {
4
- if (queue[executionIndex]) {
5
- throw new Error(`${executionIndex} already used`);
6
- }
7
-
8
- let allBeforeAreDone = true;
9
- if (executionIndex > 0) {
10
- let beforeIndex = executionIndex - 1;
11
- do {
12
- const value = queue[beforeIndex];
13
- if (!value) {
14
- allBeforeAreDone = false;
15
- break;
16
- }
17
- } while (beforeIndex--);
18
- }
19
- if (!allBeforeAreDone) {
20
- queue[executionIndex] = callback;
21
- return;
22
- }
23
- queue[executionIndex] = true;
24
- callback();
25
- let afterIndex = executionIndex + 1;
26
- while (afterIndex < queue.length) {
27
- const value = queue[afterIndex];
28
- if (value === undefined) {
29
- break;
30
- }
31
- if (typeof value === "function") {
32
- queue[afterIndex] = true;
33
- value();
34
- }
35
- afterIndex++;
36
- }
37
- };
38
- return callWhenPreviousExecutionAreDone;
39
- };
@@ -1,29 +0,0 @@
1
- export const createDetailedMessage = (message, details = {}) => {
2
- let text = `${message}`;
3
- const namedSectionsText = renderNamedSections(details);
4
- if (namedSectionsText) {
5
- text += `
6
- ${namedSectionsText}`;
7
- }
8
- return text;
9
- };
10
-
11
- export const renderNamedSections = (namedSections) => {
12
- let text = "";
13
- let keys = Object.keys(namedSections);
14
- for (const key of keys) {
15
- const isLastKey = key === keys[keys.length - 1];
16
- const value = namedSections[key];
17
- text += `--- ${key} ---
18
- ${
19
- Array.isArray(value)
20
- ? value.join(`
21
- `)
22
- : value
23
- }`;
24
- if (!isLastKey) {
25
- text += "\n";
26
- }
27
- }
28
- return text;
29
- };
@@ -1,26 +0,0 @@
1
- import { ANSI } from "../ansi/ansi_node.js";
2
-
3
- export const renderDetails = (data) => {
4
- const details = [];
5
- for (const key of Object.keys(data)) {
6
- const value = data[key];
7
- let valueString = "";
8
- valueString += ANSI.color(`${key}:`, ANSI.GREY);
9
- const useNonGreyAnsiColor =
10
- typeof value === "string" && value.includes("\x1b");
11
- valueString += " ";
12
- valueString += useNonGreyAnsiColor
13
- ? value
14
- : ANSI.color(String(value), ANSI.GREY);
15
- details.push(valueString);
16
- }
17
- if (details.length === 0) {
18
- return "";
19
- }
20
-
21
- let string = "";
22
- string += ` ${ANSI.color("(", ANSI.GREY)}`;
23
- string += details.join(ANSI.color(", ", ANSI.GREY));
24
- string += ANSI.color(")", ANSI.GREY);
25
- return string;
26
- };
@@ -1,186 +0,0 @@
1
- /*
2
- * see also https://github.com/vadimdemedes/ink
3
- */
4
-
5
- import { measureTextWidth } from "@jsenv/terminal-text-size";
6
- import ansiEscapes from "ansi-escapes";
7
-
8
- export const createDynamicLog = ({
9
- stream = process.stdout,
10
- clearTerminalAllowed,
11
- onVerticalOverflow = () => {},
12
- onWriteFromOutside = () => {},
13
- } = {}) => {
14
- const { columns = 80, rows = 24 } = stream;
15
- const dynamicLog = {
16
- destroyed: false,
17
- onVerticalOverflow,
18
- onWriteFromOutside,
19
- };
20
-
21
- let lastOutput = "";
22
- let lastOutputFromOutside = "";
23
- let clearAttemptResult;
24
- let writing = false;
25
-
26
- const getErasePreviousOutput = () => {
27
- // nothing to clear
28
- if (!lastOutput) {
29
- return "";
30
- }
31
- if (clearAttemptResult !== undefined) {
32
- return "";
33
- }
34
-
35
- const logLines = lastOutput.split(/\r\n|\r|\n/);
36
- let visualLineCount = 0;
37
- for (const logLine of logLines) {
38
- const width = measureTextWidth(logLine);
39
- if (width === 0) {
40
- visualLineCount++;
41
- } else {
42
- visualLineCount += Math.ceil(width / columns);
43
- }
44
- }
45
-
46
- if (visualLineCount > rows) {
47
- if (clearTerminalAllowed) {
48
- clearAttemptResult = true;
49
- return ansiEscapes.clearTerminal;
50
- }
51
- // the whole log cannot be cleared because it's vertically to long
52
- // (longer than terminal height)
53
- // readline.moveCursor cannot move cursor higher than screen height
54
- // it means we would only clear the visible part of the log
55
- // better keep the log untouched
56
- clearAttemptResult = false;
57
- dynamicLog.onVerticalOverflow();
58
- return "";
59
- }
60
-
61
- clearAttemptResult = true;
62
- return ansiEscapes.eraseLines(visualLineCount);
63
- };
64
-
65
- const update = (string) => {
66
- if (dynamicLog.destroyed) {
67
- throw new Error("Cannot write log after destroy");
68
- }
69
- let stringToWrite = string;
70
- if (lastOutput) {
71
- if (lastOutputFromOutside) {
72
- // We don't want to clear logs written by other code,
73
- // it makes output unreadable and might erase precious information
74
- // To detect this we put a spy on the stream.
75
- // The spy is required only if we actually wrote something in the stream
76
- // something else than this code has written in the stream
77
- // so we just write without clearing (append instead of replacing)
78
- lastOutput = "";
79
- lastOutputFromOutside = "";
80
- } else {
81
- stringToWrite = `${getErasePreviousOutput()}${string}`;
82
- }
83
- }
84
- writing = true;
85
- stream.write(stringToWrite);
86
- lastOutput = string;
87
- writing = false;
88
- clearAttemptResult = undefined;
89
- };
90
-
91
- const clearDuringFunctionCall = (
92
- callback,
93
- ouputAfterCallback = lastOutput,
94
- ) => {
95
- // 1. Erase the current log
96
- // 2. Call callback (expect to write something on stdout)
97
- // 3. Restore the current log
98
- // During step 2. we expect a "write from outside" so we uninstall
99
- // the stream spy during function call
100
- update("");
101
-
102
- writing = true;
103
- callback(update);
104
- lastOutput = "";
105
- writing = false;
106
-
107
- update(ouputAfterCallback);
108
- };
109
-
110
- const writeFromOutsideEffect = (value) => {
111
- if (!lastOutput) {
112
- // we don't care if the log never wrote anything
113
- // or if last update() wrote an empty string
114
- return;
115
- }
116
- if (writing) {
117
- return;
118
- }
119
- lastOutputFromOutside = value;
120
- dynamicLog.onWriteFromOutside(value);
121
- };
122
-
123
- let removeStreamSpy;
124
- if (stream === process.stdout) {
125
- const removeStdoutSpy = spyStreamOutput(
126
- process.stdout,
127
- writeFromOutsideEffect,
128
- );
129
- const removeStderrSpy = spyStreamOutput(
130
- process.stderr,
131
- writeFromOutsideEffect,
132
- );
133
- removeStreamSpy = () => {
134
- removeStdoutSpy();
135
- removeStderrSpy();
136
- };
137
- } else {
138
- removeStreamSpy = spyStreamOutput(stream, writeFromOutsideEffect);
139
- }
140
-
141
- const destroy = () => {
142
- dynamicLog.destroyed = true;
143
- if (removeStreamSpy) {
144
- removeStreamSpy();
145
- removeStreamSpy = null;
146
- lastOutput = "";
147
- lastOutputFromOutside = "";
148
- }
149
- };
150
-
151
- Object.assign(dynamicLog, {
152
- update,
153
- destroy,
154
- stream,
155
- clearDuringFunctionCall,
156
- });
157
- return dynamicLog;
158
- };
159
-
160
- // maybe https://github.com/gajus/output-interceptor/tree/v3.0.0 ?
161
- // the problem with listening data on stdout
162
- // is that node.js will later throw error if stream gets closed
163
- // while something listening data on it
164
- const spyStreamOutput = (stream, callback) => {
165
- let output = "";
166
- let installed = true;
167
- const originalWrite = stream.write;
168
- stream.write = function (...args /* chunk, encoding, callback */) {
169
- output += args;
170
- callback(output);
171
- return originalWrite.call(this, ...args);
172
- };
173
-
174
- const uninstall = () => {
175
- if (!installed) {
176
- return;
177
- }
178
- stream.write = originalWrite;
179
- installed = false;
180
- };
181
-
182
- return () => {
183
- uninstall();
184
- return output;
185
- };
186
- };