@mark1russell7/text 0.0.17 → 0.0.19
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/README.md +41 -0
- package/build/error-6yypUDJz.js +37 -0
- package/build/error-6yypUDJz.js.map +1 -0
- package/build/index.js +1 -36
- package/build/passage.d.ts +34 -0
- package/build/passage.d.ts.map +1 -0
- package/build/passage.js +91 -0
- package/build/passage.js.map +1 -0
- package/build/print.d.ts +51 -0
- package/build/print.d.ts.map +1 -0
- package/build/print.js +55 -0
- package/build/print.js.map +1 -0
- package/package.json +13 -2
- package/src/passage.ts +96 -0
- package/src/print.ts +93 -0
- package/build/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -40,6 +40,29 @@ escapeShell("my file's name"); // "'my file'\\''s name'"
|
|
|
40
40
|
escapeShell("$HOME"); // "'$HOME'"
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
+
## The output of a command-line tool
|
|
44
|
+
|
|
45
|
+
`createPrinter({ out, err?, secrets? })` gives a printer of the output of a command-line tool, for a person. `out` and `err` are streams with `write(text)`, for example `process.stdout` and `process.stderr`. The default of `err` is `out`. The entry imports no `node:` module, so a test can give a buffer in place of a stream.
|
|
46
|
+
|
|
47
|
+
- `line(text?)` writes a line to `out`.
|
|
48
|
+
- `table(rows, { head?, align?, gap? })` writes a table to `out`. It measures each cell in graphemes, and a line has no spaces at its end. The align `end` puts a column at the right, for numbers.
|
|
49
|
+
- `status(state, text)` writes `OK`, `INFO`, `WARN` or `FAIL` and the text. The state `fail` goes to `err`, and the other states go to `out`.
|
|
50
|
+
- `warn(text)` writes `warning: ` and the text to `err`.
|
|
51
|
+
- `error(thrown, context?)` writes the text of a thrown value (`errorMessage`) to `err`. A context comes before the text. It does not throw.
|
|
52
|
+
- `json(value)` writes the value as JSON with two spaces, to `out`.
|
|
53
|
+
|
|
54
|
+
Before each write, the printer puts `[secret]` in place of each known secret of `secrets` (`redactSecrets`) and each shape of a token (`redactSecretShapes`).
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { createPrinter } from "@mark1russell7/text/print";
|
|
58
|
+
|
|
59
|
+
const print = createPrinter({ out: process.stdout, err: process.stderr });
|
|
60
|
+
print.table([["alerts", 82], ["fleet", 121]], { head: ["repository", "calls"], align: ["start", "end"] });
|
|
61
|
+
print.status("fail", "test: 2 errors");
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The printer is for output that a person reads. A diagnostic of a library or a service (a warning, a debug line, a caught error) is not output. Send it to a log record with its trace context, through the logger of OpenTelemetry.
|
|
65
|
+
|
|
43
66
|
## English word forms
|
|
44
67
|
|
|
45
68
|
`countOf(count, noun, plural?)` gives a count with a noun. Only the count 1 takes the singular noun. The default plural noun is the singular noun with "s" at the end.
|
|
@@ -97,6 +120,23 @@ const corpus = ["The release gate", "The topic graph of the site", "A graph page
|
|
|
97
120
|
rankDocuments(corpus, searchWords("topic graph")); // [{ index: 1, … }, { index: 2, … }, { index: 0, score: 0 }]
|
|
98
121
|
```
|
|
99
122
|
|
|
123
|
+
### A passage in a text
|
|
124
|
+
|
|
125
|
+
The entry `@mark1russell7/text/passage` finds a passage in a text, for example a quote in the text of its source. Since 0.0.18.
|
|
126
|
+
|
|
127
|
+
- `passageKey(text)` gives the key of a text. It applies `searchKey` to each grapheme and removes the characters with no width.
|
|
128
|
+
- The key changes each curly quote to a straight quote, each dash to a hyphen-minus, and each run of white space to one space.
|
|
129
|
+
- `findPassage(text, passage)` gives the first span `{ start, end }` of the passage in the text, or `undefined`.
|
|
130
|
+
- The span is in the text, not in the key. Thus `text.slice(start, end)` gives the words of the source.
|
|
131
|
+
- Accents and punctuation stay. A hyphen at the end of a line stays, because it can be a real hyphen.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { findPassage } from "@mark1russell7/text/passage";
|
|
135
|
+
|
|
136
|
+
const text = "Water boils at lower\ntemperatures as altitude increases.";
|
|
137
|
+
findPassage(text, "water boils at lower temperatures"); // { start: 0, end: 33 }
|
|
138
|
+
```
|
|
139
|
+
|
|
100
140
|
## The order of texts
|
|
101
141
|
|
|
102
142
|
The entry `@mark1russell7/text/order` has two orders of texts. Each order is the same in each locale and in each copy of a program. The name of each function tells its unit.
|
|
@@ -337,6 +377,7 @@ The tests also examine 18 copies of a cut with a mark, from a later list of the
|
|
|
337
377
|
- `escapeShell` gives one word for a POSIX shell, not for `cmd.exe` or PowerShell. It throws a `RangeError` for a text with NUL.
|
|
338
378
|
- `wordSearch` keeps accents, so "cafe" does not find "café".
|
|
339
379
|
- `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
|
|
380
|
+
- `createPrinter` does not color the output and does not wrap a long line.
|
|
340
381
|
- `listOf` does not change the parts. A part with a comma makes a list that a reader cannot split again.
|
|
341
382
|
- `errorMessage` gives only the message. It does not add the name of the error, its `cause` or its stack.
|
|
342
383
|
- `redactSecrets` removes only the forms in its table. A secret in a JSON string with escapes, or in a different encoding, stays.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/error.ts
|
|
2
|
+
/**
|
|
3
|
+
* This module has the text of a thrown value.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.
|
|
7
|
+
*
|
|
8
|
+
* - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error
|
|
9
|
+
* from another realm (a `vm` context or an `iframe`) also gives its message.
|
|
10
|
+
* - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of
|
|
11
|
+
* `Object.prototype.toString` finds an `Error` of each realm.
|
|
12
|
+
* - Each other value gives `String(value)`.
|
|
13
|
+
* - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.
|
|
14
|
+
* - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.
|
|
15
|
+
*
|
|
16
|
+
* @param error - The thrown value. It can be any value.
|
|
17
|
+
* @returns The text of the value.
|
|
18
|
+
*/
|
|
19
|
+
function errorMessage(error) {
|
|
20
|
+
try {
|
|
21
|
+
if (typeof error === "object" && error !== null && "message" in error) {
|
|
22
|
+
const message = error.message;
|
|
23
|
+
if (typeof message === "string") return message;
|
|
24
|
+
if (Object.prototype.toString.call(error) === "[object Error]") return String(message);
|
|
25
|
+
}
|
|
26
|
+
return String(error);
|
|
27
|
+
} catch {
|
|
28
|
+
try {
|
|
29
|
+
return Object.prototype.toString.call(error);
|
|
30
|
+
} catch {
|
|
31
|
+
return `[${typeof error}]`;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export { errorMessage as t };
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=error-6yypUDJz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-6yypUDJz.js","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF"}
|
package/build/index.js
CHANGED
|
@@ -1,40 +1,5 @@
|
|
|
1
1
|
import { countOf } from "./english.js";
|
|
2
|
+
import { t as errorMessage } from "./error-6yypUDJz.js";
|
|
2
3
|
import { a as escapeWorkflowData, i as escapeRegExp, n as escapeHtml, o as escapeWorkflowProperty, r as escapeMarkdown, t as escapeAttribute } from "./escape-vfOeIxac.js";
|
|
3
4
|
import { searchKey, wordSearch } from "./search.js";
|
|
4
|
-
// src/error.ts
|
|
5
|
-
/**
|
|
6
|
-
* This module has the text of a thrown value.
|
|
7
|
-
*/
|
|
8
|
-
/**
|
|
9
|
-
* This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.
|
|
10
|
-
*
|
|
11
|
-
* - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error
|
|
12
|
-
* from another realm (a `vm` context or an `iframe`) also gives its message.
|
|
13
|
-
* - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of
|
|
14
|
-
* `Object.prototype.toString` finds an `Error` of each realm.
|
|
15
|
-
* - Each other value gives `String(value)`.
|
|
16
|
-
* - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.
|
|
17
|
-
* - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.
|
|
18
|
-
*
|
|
19
|
-
* @param error - The thrown value. It can be any value.
|
|
20
|
-
* @returns The text of the value.
|
|
21
|
-
*/
|
|
22
|
-
function errorMessage(error) {
|
|
23
|
-
try {
|
|
24
|
-
if (typeof error === "object" && error !== null && "message" in error) {
|
|
25
|
-
const message = error.message;
|
|
26
|
-
if (typeof message === "string") return message;
|
|
27
|
-
if (Object.prototype.toString.call(error) === "[object Error]") return String(message);
|
|
28
|
-
}
|
|
29
|
-
return String(error);
|
|
30
|
-
} catch {
|
|
31
|
-
try {
|
|
32
|
-
return Object.prototype.toString.call(error);
|
|
33
|
-
} catch {
|
|
34
|
-
return `[${typeof error}]`;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
5
|
export { countOf, errorMessage, escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty, searchKey, wordSearch };
|
|
39
|
-
|
|
40
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This function gives the key of a text for a passage search. `findPassage` compares the keys of two texts. The function
|
|
3
|
+
* does these steps on each grapheme of the text:
|
|
4
|
+
*
|
|
5
|
+
* 1. It removes the characters with no width: the soft hyphen, the zero-width space, the joiners and the byte order mark.
|
|
6
|
+
* 2. It applies `searchKey`. Thus the case of the letters and the NFKC forms are not significant.
|
|
7
|
+
* 3. It changes each curly or low quote mark and each prime to the apostrophe or to the double quote. It changes each dash and the minus sign to the hyphen-minus.
|
|
8
|
+
* 4. It changes each run of white space to one space, and it removes the white space at the start and at the end.
|
|
9
|
+
*
|
|
10
|
+
* Accents and punctuation stay. A hyphen at the end of a line stays, because the function cannot tell it from a real hyphen.
|
|
11
|
+
*
|
|
12
|
+
* @param text - The plain text.
|
|
13
|
+
* @returns The key of the text.
|
|
14
|
+
*/
|
|
15
|
+
export declare function passageKey(text: string): string;
|
|
16
|
+
/** The place of a passage in a text, in UTF-16 code units. The passage is `text.slice(start, end)`. */
|
|
17
|
+
export interface PassageSpan {
|
|
18
|
+
readonly start: number;
|
|
19
|
+
readonly end: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* This function finds a passage in a text, for example a quote in the text of its source. It has no I/O.
|
|
23
|
+
*
|
|
24
|
+
* - The text holds the passage when the key of the text (`passageKey`) contains the key of the passage.
|
|
25
|
+
* - The result is the first place, from the start of the first grapheme to the end of the last grapheme of the match.
|
|
26
|
+
* - A passage can start or end inside a word, as in `wordSearch`. The caller tests the edges when a word must be whole.
|
|
27
|
+
* - A passage with an empty key, for example only white space, gives `undefined`. It is not a match at 0.
|
|
28
|
+
*
|
|
29
|
+
* @param text - The text to search, for example the text of a source.
|
|
30
|
+
* @param passage - The passage, for example a quote.
|
|
31
|
+
* @returns The span of the passage in the text, or `undefined` when the text does not hold it.
|
|
32
|
+
*/
|
|
33
|
+
export declare function findPassage(text: string, passage: string): PassageSpan | undefined;
|
|
34
|
+
//# sourceMappingURL=passage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"passage.d.ts","names":[],"sources":["../src/passage.ts"],"mappings":";;;;;;;;;;;;;;wBAkEgB,WAAW;;iBAKV;WACN;WACA;;;;;;;;;;;;;;wBAeK,YAAY,cAAc,kBAAkB"}
|
package/build/passage.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { searchKey } from "./search.js";
|
|
2
|
+
// src/passage.ts
|
|
3
|
+
/**
|
|
4
|
+
* This module finds a passage in a text, for example a quote in the text of its source. The key of a text
|
|
5
|
+
* (`passageKey`) makes the case, the quote marks, the dashes and the white space not significant. `findPassage` gives
|
|
6
|
+
* the span of the passage in the text. Each function has no I/O.
|
|
7
|
+
*/
|
|
8
|
+
/** The quote marks that `passageKey` changes to the apostrophe: the single quotes, the low and the reversed single quotes, and the prime. */
|
|
9
|
+
const SINGLE_QUOTES = /[\u2018\u2019\u201A\u201B\u2032\u02BC]/gu;
|
|
10
|
+
/** The quote marks that `passageKey` changes to the double quote: the double quotes, the low and the reversed double quotes and the guillemets. NFKC changes a double prime to two primes. */
|
|
11
|
+
const DOUBLE_QUOTES = /[\u201C\u201D\u201E\u201F\u00AB\u00BB]/gu;
|
|
12
|
+
/** The dashes that `passageKey` changes to the hyphen-minus. They are the hyphen, the non-breaking hyphen, the figure dash, the en dash and the em dash, the bar and the minus sign. */
|
|
13
|
+
const DASHES = /[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/gu;
|
|
14
|
+
/** The characters with no width that `passageKey` removes: the soft hyphen, the zero-width space, the joiners and the byte order mark. */
|
|
15
|
+
const NO_WIDTH = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/gu;
|
|
16
|
+
/** A grapheme of white space only. */
|
|
17
|
+
const SPACE = /^\s+$/u;
|
|
18
|
+
/** The grapheme segmenter of `passageKey` and `findPassage`. The module makes it one time, at the first use. */
|
|
19
|
+
let graphemeSegmenter;
|
|
20
|
+
/** This function gives the key of a text and the place of each code unit of the key in the text. */
|
|
21
|
+
function passageParts(text) {
|
|
22
|
+
graphemeSegmenter ??= new Intl.Segmenter("en", { granularity: "grapheme" });
|
|
23
|
+
let key = "";
|
|
24
|
+
const starts = [];
|
|
25
|
+
const ends = [];
|
|
26
|
+
for (const { segment, index } of graphemeSegmenter.segment(text)) {
|
|
27
|
+
const clean = segment.replace(NO_WIDTH, "");
|
|
28
|
+
let part;
|
|
29
|
+
if (clean === "") part = "";
|
|
30
|
+
else if (SPACE.test(clean)) part = key === "" || key.endsWith(" ") ? "" : " ";
|
|
31
|
+
else part = searchKey(clean).replace(SINGLE_QUOTES, "'").replace(DOUBLE_QUOTES, "\"").replace(DASHES, "-");
|
|
32
|
+
for (let unit = 0; unit < part.length; unit++) {
|
|
33
|
+
starts.push(index);
|
|
34
|
+
ends.push(index + segment.length);
|
|
35
|
+
}
|
|
36
|
+
key += part;
|
|
37
|
+
}
|
|
38
|
+
if (key.endsWith(" ")) return {
|
|
39
|
+
key: key.slice(0, -1),
|
|
40
|
+
starts: starts.slice(0, -1),
|
|
41
|
+
ends: ends.slice(0, -1)
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
key,
|
|
45
|
+
starts,
|
|
46
|
+
ends
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* This function gives the key of a text for a passage search. `findPassage` compares the keys of two texts. The function
|
|
51
|
+
* does these steps on each grapheme of the text:
|
|
52
|
+
*
|
|
53
|
+
* 1. It removes the characters with no width: the soft hyphen, the zero-width space, the joiners and the byte order mark.
|
|
54
|
+
* 2. It applies `searchKey`. Thus the case of the letters and the NFKC forms are not significant.
|
|
55
|
+
* 3. It changes each curly or low quote mark and each prime to the apostrophe or to the double quote. It changes each dash and the minus sign to the hyphen-minus.
|
|
56
|
+
* 4. It changes each run of white space to one space, and it removes the white space at the start and at the end.
|
|
57
|
+
*
|
|
58
|
+
* Accents and punctuation stay. A hyphen at the end of a line stays, because the function cannot tell it from a real hyphen.
|
|
59
|
+
*
|
|
60
|
+
* @param text - The plain text.
|
|
61
|
+
* @returns The key of the text.
|
|
62
|
+
*/
|
|
63
|
+
function passageKey(text) {
|
|
64
|
+
return passageParts(text).key;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* This function finds a passage in a text, for example a quote in the text of its source. It has no I/O.
|
|
68
|
+
*
|
|
69
|
+
* - The text holds the passage when the key of the text (`passageKey`) contains the key of the passage.
|
|
70
|
+
* - The result is the first place, from the start of the first grapheme to the end of the last grapheme of the match.
|
|
71
|
+
* - A passage can start or end inside a word, as in `wordSearch`. The caller tests the edges when a word must be whole.
|
|
72
|
+
* - A passage with an empty key, for example only white space, gives `undefined`. It is not a match at 0.
|
|
73
|
+
*
|
|
74
|
+
* @param text - The text to search, for example the text of a source.
|
|
75
|
+
* @param passage - The passage, for example a quote.
|
|
76
|
+
* @returns The span of the passage in the text, or `undefined` when the text does not hold it.
|
|
77
|
+
*/
|
|
78
|
+
function findPassage(text, passage) {
|
|
79
|
+
const needle = passageKey(passage);
|
|
80
|
+
if (needle === "") return void 0;
|
|
81
|
+
const parts = passageParts(text);
|
|
82
|
+
const at = parts.key.indexOf(needle);
|
|
83
|
+
if (at < 0) return void 0;
|
|
84
|
+
return {
|
|
85
|
+
start: parts.starts[at] ?? 0,
|
|
86
|
+
end: parts.ends[at + needle.length - 1] ?? 0
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
export { findPassage, passageKey };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=passage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"passage.js","names":[],"sources":["../src/passage.ts"],"sourcesContent":["/**\n * This module finds a passage in a text, for example a quote in the text of its source. The key of a text\n * (`passageKey`) makes the case, the quote marks, the dashes and the white space not significant. `findPassage` gives\n * the span of the passage in the text. Each function has no I/O.\n */\n\nimport { searchKey } from \"./search.ts\";\n\n/** The quote marks that `passageKey` changes to the apostrophe: the single quotes, the low and the reversed single quotes, and the prime. */\nconst SINGLE_QUOTES = /[\\u2018\\u2019\\u201A\\u201B\\u2032\\u02BC]/gu;\n/** The quote marks that `passageKey` changes to the double quote: the double quotes, the low and the reversed double quotes and the guillemets. NFKC changes a double prime to two primes. */\nconst DOUBLE_QUOTES = /[\\u201C\\u201D\\u201E\\u201F\\u00AB\\u00BB]/gu;\n/** The dashes that `passageKey` changes to the hyphen-minus. They are the hyphen, the non-breaking hyphen, the figure dash, the en dash and the em dash, the bar and the minus sign. */\nconst DASHES = /[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/gu;\n/** The characters with no width that `passageKey` removes: the soft hyphen, the zero-width space, the joiners and the byte order mark. */\nconst NO_WIDTH = /[\\u00AD\\u200B\\u200C\\u200D\\u2060\\uFEFF]/gu;\n/** A grapheme of white space only. */\nconst SPACE = /^\\s+$/u;\n\n/** The grapheme segmenter of `passageKey` and `findPassage`. The module makes it one time, at the first use. */\nlet graphemeSegmenter: Intl.Segmenter | undefined;\n\n/** The key of a text for a passage search, with the start and the end in the text of each code unit of the key. */\ninterface PassageParts {\n readonly key: string;\n readonly starts: readonly number[];\n readonly ends: readonly number[];\n}\n\n/** This function gives the key of a text and the place of each code unit of the key in the text. */\nfunction passageParts(text: string): PassageParts {\n graphemeSegmenter ??= new Intl.Segmenter(\"en\", { granularity: \"grapheme\" });\n let key = \"\";\n const starts: number[] = [];\n const ends: number[] = [];\n for (const { segment, index } of graphemeSegmenter.segment(text)) {\n // A joiner is a part of the grapheme before it, so the test of white space comes after the removal.\n const clean = segment.replace(NO_WIDTH, \"\");\n let part: string;\n if (clean === \"\") part = \"\";\n else if (SPACE.test(clean)) part = key === \"\" || key.endsWith(\" \") ? \"\" : \" \";\n else part = searchKey(clean).replace(SINGLE_QUOTES, \"'\").replace(DOUBLE_QUOTES, '\"').replace(DASHES, \"-\");\n for (let unit = 0; unit < part.length; unit++) {\n starts.push(index);\n ends.push(index + segment.length);\n }\n key += part;\n }\n if (key.endsWith(\" \")) return { key: key.slice(0, -1), starts: starts.slice(0, -1), ends: ends.slice(0, -1) };\n return { key, starts, ends };\n}\n\n/**\n * This function gives the key of a text for a passage search. `findPassage` compares the keys of two texts. The function\n * does these steps on each grapheme of the text:\n *\n * 1. It removes the characters with no width: the soft hyphen, the zero-width space, the joiners and the byte order mark.\n * 2. It applies `searchKey`. Thus the case of the letters and the NFKC forms are not significant.\n * 3. It changes each curly or low quote mark and each prime to the apostrophe or to the double quote. It changes each dash and the minus sign to the hyphen-minus.\n * 4. It changes each run of white space to one space, and it removes the white space at the start and at the end.\n *\n * Accents and punctuation stay. A hyphen at the end of a line stays, because the function cannot tell it from a real hyphen.\n *\n * @param text - The plain text.\n * @returns The key of the text.\n */\nexport function passageKey(text: string): string {\n return passageParts(text).key;\n}\n\n/** The place of a passage in a text, in UTF-16 code units. The passage is `text.slice(start, end)`. */\nexport interface PassageSpan {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * This function finds a passage in a text, for example a quote in the text of its source. It has no I/O.\n *\n * - The text holds the passage when the key of the text (`passageKey`) contains the key of the passage.\n * - The result is the first place, from the start of the first grapheme to the end of the last grapheme of the match.\n * - A passage can start or end inside a word, as in `wordSearch`. The caller tests the edges when a word must be whole.\n * - A passage with an empty key, for example only white space, gives `undefined`. It is not a match at 0.\n *\n * @param text - The text to search, for example the text of a source.\n * @param passage - The passage, for example a quote.\n * @returns The span of the passage in the text, or `undefined` when the text does not hold it.\n */\nexport function findPassage(text: string, passage: string): PassageSpan | undefined {\n const needle = passageKey(passage);\n if (needle === \"\") return undefined;\n const parts = passageParts(text);\n const at = parts.key.indexOf(needle);\n if (at < 0) return undefined;\n return { start: parts.starts[at] ?? 0, end: parts.ends[at + needle.length - 1] ?? 0 };\n}\n"],"mappings":";;;;;;;;AASA,MAAM,gBAAgB;;AAEtB,MAAM,gBAAgB;;AAEtB,MAAM,SAAS;;AAEf,MAAM,WAAW;;AAEjB,MAAM,QAAQ;;AAGd,IAAI;;AAUJ,SAAS,aAAa,MAA4B;CAChD,sBAAsB,IAAI,KAAK,UAAU,MAAM,EAAE,aAAa,WAAW,CAAC;CAC1E,IAAI,MAAM;CACV,MAAM,SAAmB,CAAC;CAC1B,MAAM,OAAiB,CAAC;CACxB,KAAK,MAAM,EAAE,SAAS,WAAW,kBAAkB,QAAQ,IAAI,GAAG;EAEhE,MAAM,QAAQ,QAAQ,QAAQ,UAAU,EAAE;EAC1C,IAAI;EACJ,IAAI,UAAU,IAAI,OAAO;OACpB,IAAI,MAAM,KAAK,KAAK,GAAG,OAAO,QAAQ,MAAM,IAAI,SAAS,GAAG,IAAI,KAAK;OACrE,OAAO,UAAU,KAAK,CAAC,CAAC,QAAQ,eAAe,GAAG,CAAC,CAAC,QAAQ,eAAe,IAAG,CAAC,CAAC,QAAQ,QAAQ,GAAG;EACxG,KAAK,IAAI,OAAO,GAAG,OAAO,KAAK,QAAQ,QAAQ;GAC7C,OAAO,KAAK,KAAK;GACjB,KAAK,KAAK,QAAQ,QAAQ,MAAM;EAClC;EACA,OAAO;CACT;CACA,IAAI,IAAI,SAAS,GAAG,GAAG,OAAO;EAAE,KAAK,IAAI,MAAM,GAAG,EAAE;EAAG,QAAQ,OAAO,MAAM,GAAG,EAAE;EAAG,MAAM,KAAK,MAAM,GAAG,EAAE;CAAE;CAC5G,OAAO;EAAE;EAAK;EAAQ;CAAK;AAC7B;;;;;;;;;;;;;;;AAgBA,SAAgB,WAAW,MAAsB;CAC/C,OAAO,aAAa,IAAI,CAAC,CAAC;AAC5B;;;;;;;;;;;;;AAoBA,SAAgB,YAAY,MAAc,SAA0C;CAClF,MAAM,SAAS,WAAW,OAAO;CACjC,IAAI,WAAW,IAAI,OAAO,KAAA;CAC1B,MAAM,QAAQ,aAAa,IAAI;CAC/B,MAAM,KAAK,MAAM,IAAI,QAAQ,MAAM;CACnC,IAAI,KAAK,GAAG,OAAO,KAAA;CACnB,OAAO;EAAE,OAAO,MAAM,OAAO,OAAO;EAAG,KAAK,MAAM,KAAK,KAAK,OAAO,SAAS,MAAM;CAAE;AACtF"}
|
package/build/print.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Secret } from "./redact.js";
|
|
2
|
+
/** A stream of text, for example `process.stdout`. The printer uses only its `write`. */
|
|
3
|
+
export interface TextSink {
|
|
4
|
+
write(text: string): unknown;
|
|
5
|
+
}
|
|
6
|
+
/** The options of `createPrinter`. */
|
|
7
|
+
export interface PrinterOptions {
|
|
8
|
+
/** The stream of the output, for example `process.stdout`. */
|
|
9
|
+
readonly out: TextSink;
|
|
10
|
+
/** The stream of the errors and warnings, for example `process.stderr`. The default is `out`. */
|
|
11
|
+
readonly err?: TextSink;
|
|
12
|
+
/** The known secrets, for example the tokens of the command. The printer puts a mark in place of each before a write. */
|
|
13
|
+
readonly secrets?: readonly Secret[];
|
|
14
|
+
}
|
|
15
|
+
/** The side of a column of a table. `end` aligns the cells at the right, for numbers. */
|
|
16
|
+
export type ColumnAlign = "start" | "end";
|
|
17
|
+
/** The options of `Printer.table`. */
|
|
18
|
+
export interface TableOptions {
|
|
19
|
+
/** The head of each column. The printer writes it as the first row. */
|
|
20
|
+
readonly head?: readonly string[];
|
|
21
|
+
/** The side of each column. The default is `start` for each column. */
|
|
22
|
+
readonly align?: readonly ColumnAlign[];
|
|
23
|
+
/** The text between two columns. The default is two spaces. */
|
|
24
|
+
readonly gap?: string;
|
|
25
|
+
}
|
|
26
|
+
/** The state of a status line. */
|
|
27
|
+
export type StatusState = "ok" | "fail" | "warn" | "info";
|
|
28
|
+
/** A printer of the output of a command-line tool. */
|
|
29
|
+
export interface Printer {
|
|
30
|
+
/** This function writes a line to `out`. No text gives an empty line. */
|
|
31
|
+
line(text?: string): void;
|
|
32
|
+
/** This function writes a table to `out`. A cell is any value, and `String` gives its text. */
|
|
33
|
+
table(rows: readonly (readonly unknown[])[], options?: TableOptions): void;
|
|
34
|
+
/** This function writes a status line to `out`, for example `FAIL build: 2 errors`. The state `fail` goes to `err`. */
|
|
35
|
+
status(state: StatusState, text: string): void;
|
|
36
|
+
/** This function writes a warning line to `err`. */
|
|
37
|
+
warn(text: string): void;
|
|
38
|
+
/** This function writes the text of a thrown value to `err`. It does not throw. A `context` comes before the text. */
|
|
39
|
+
error(error: unknown, context?: string): void;
|
|
40
|
+
/** This function writes a value as JSON with two spaces, to `out`. It throws as `JSON.stringify` does, for a bigint or a cycle. */
|
|
41
|
+
json(value: unknown): void;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* This function makes a printer that writes to the streams of `options`. Each write puts a mark in place of each known
|
|
45
|
+
* secret and of each shape of a token (`redactSecretShapes`), and ends with a new line.
|
|
46
|
+
*
|
|
47
|
+
* @param options - The streams and the known secrets.
|
|
48
|
+
* @returns The printer.
|
|
49
|
+
*/
|
|
50
|
+
export declare function createPrinter(options: PrinterOptions): Printer;
|
|
51
|
+
//# sourceMappingURL=print.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"print.d.ts","names":[],"sources":["../src/print.ts"],"mappings":";;iBAciB;EACf,MAAM;;;iBAIS;;WAEN,KAAK;;WAEL,MAAM;;WAEN,mBAAmB;;;YAIlB;;iBAGK;;WAEN;;WAEA,iBAAiB;;WAEjB;;;YAIC;;iBAGK;;EAEf,KAAK;;EAEL,MAAM,uCAAuC,UAAU;;EAEvD,OAAO,OAAO,aAAa;;EAE3B,KAAK;;EAEL,MAAM,gBAAgB;;EAEtB,KAAK;;;;;;;;;wBAYS,cAAc,SAAS,iBAAiB"}
|
package/build/print.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { t as errorMessage } from "./error-6yypUDJz.js";
|
|
2
|
+
import { pad, textLength } from "./length.js";
|
|
3
|
+
import { redactSecretShapes, redactSecrets } from "./redact.js";
|
|
4
|
+
// src/print.ts
|
|
5
|
+
/**
|
|
6
|
+
* The entry `@mark1russell7/text/print`: the printer of the output of a command-line tool for a person. It writes lines,
|
|
7
|
+
* tables, status lines and the text of a thrown value to streams that the caller gives. Thus the entry imports no `node:`
|
|
8
|
+
* module, and a test gives a buffer in place of a stream.
|
|
9
|
+
*
|
|
10
|
+
* The printer is for output that a person reads: the text, the tables and the status lines of a CLI. A diagnostic of a
|
|
11
|
+
* library or a service (a warning, a debug line, a caught error) is not output. It goes to a log record with its trace
|
|
12
|
+
* context, through the logger of OpenTelemetry, and not to a printer.
|
|
13
|
+
*/
|
|
14
|
+
const MARKS = {
|
|
15
|
+
ok: "OK ",
|
|
16
|
+
fail: "FAIL",
|
|
17
|
+
warn: "WARN",
|
|
18
|
+
info: "INFO"
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* This function makes a printer that writes to the streams of `options`. Each write puts a mark in place of each known
|
|
22
|
+
* secret and of each shape of a token (`redactSecretShapes`), and ends with a new line.
|
|
23
|
+
*
|
|
24
|
+
* @param options - The streams and the known secrets.
|
|
25
|
+
* @returns The printer.
|
|
26
|
+
*/
|
|
27
|
+
function createPrinter(options) {
|
|
28
|
+
const { out, err = out, secrets = [] } = options;
|
|
29
|
+
const write = (sink, text) => {
|
|
30
|
+
sink.write(`${redactSecretShapes(secrets.length > 0 ? redactSecrets(text, secrets) : text)}\n`);
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
line: (text = "") => write(out, text),
|
|
34
|
+
table: (rows, table = {}) => {
|
|
35
|
+
const { head, align = [], gap = " " } = table;
|
|
36
|
+
const cells = [...head ? [head] : [], ...rows].map((row) => row.map((cell) => String(cell ?? "")));
|
|
37
|
+
const widths = [];
|
|
38
|
+
for (const row of cells) row.forEach((cell, at) => widths[at] = Math.max(widths[at] ?? 0, textLength(cell, "grapheme")));
|
|
39
|
+
for (const row of cells) {
|
|
40
|
+
const parts = row.map((cell, at) => pad(cell, widths[at] ?? 0, {
|
|
41
|
+
unit: "grapheme",
|
|
42
|
+
side: align[at] === "end" ? "start" : "end"
|
|
43
|
+
}));
|
|
44
|
+
write(out, parts.join(gap).trimEnd());
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
status: (state, text) => write(state === "fail" ? err : out, `${MARKS[state]} ${text}`),
|
|
48
|
+
warn: (text) => write(err, `warning: ${text}`),
|
|
49
|
+
error: (error, context) => write(err, context === void 0 ? errorMessage(error) : `${context}: ${errorMessage(error)}`),
|
|
50
|
+
json: (value) => write(out, JSON.stringify(value, null, 2) ?? String(value))
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export { createPrinter };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=print.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"print.js","names":[],"sources":["../src/print.ts"],"sourcesContent":["/**\n * The entry `@mark1russell7/text/print`: the printer of the output of a command-line tool for a person. It writes lines,\n * tables, status lines and the text of a thrown value to streams that the caller gives. Thus the entry imports no `node:`\n * module, and a test gives a buffer in place of a stream.\n *\n * The printer is for output that a person reads: the text, the tables and the status lines of a CLI. A diagnostic of a\n * library or a service (a warning, a debug line, a caught error) is not output. It goes to a log record with its trace\n * context, through the logger of OpenTelemetry, and not to a printer.\n */\nimport { errorMessage } from \"./error.ts\";\nimport { pad, textLength } from \"./length.ts\";\nimport { redactSecretShapes, redactSecrets, type Secret } from \"./redact.ts\";\n\n/** A stream of text, for example `process.stdout`. The printer uses only its `write`. */\nexport interface TextSink {\n write(text: string): unknown;\n}\n\n/** The options of `createPrinter`. */\nexport interface PrinterOptions {\n /** The stream of the output, for example `process.stdout`. */\n readonly out: TextSink;\n /** The stream of the errors and warnings, for example `process.stderr`. The default is `out`. */\n readonly err?: TextSink;\n /** The known secrets, for example the tokens of the command. The printer puts a mark in place of each before a write. */\n readonly secrets?: readonly Secret[];\n}\n\n/** The side of a column of a table. `end` aligns the cells at the right, for numbers. */\nexport type ColumnAlign = \"start\" | \"end\";\n\n/** The options of `Printer.table`. */\nexport interface TableOptions {\n /** The head of each column. The printer writes it as the first row. */\n readonly head?: readonly string[];\n /** The side of each column. The default is `start` for each column. */\n readonly align?: readonly ColumnAlign[];\n /** The text between two columns. The default is two spaces. */\n readonly gap?: string;\n}\n\n/** The state of a status line. */\nexport type StatusState = \"ok\" | \"fail\" | \"warn\" | \"info\";\n\n/** A printer of the output of a command-line tool. */\nexport interface Printer {\n /** This function writes a line to `out`. No text gives an empty line. */\n line(text?: string): void;\n /** This function writes a table to `out`. A cell is any value, and `String` gives its text. */\n table(rows: readonly (readonly unknown[])[], options?: TableOptions): void;\n /** This function writes a status line to `out`, for example `FAIL build: 2 errors`. The state `fail` goes to `err`. */\n status(state: StatusState, text: string): void;\n /** This function writes a warning line to `err`. */\n warn(text: string): void;\n /** This function writes the text of a thrown value to `err`. It does not throw. A `context` comes before the text. */\n error(error: unknown, context?: string): void;\n /** This function writes a value as JSON with two spaces, to `out`. It throws as `JSON.stringify` does, for a bigint or a cycle. */\n json(value: unknown): void;\n}\n\nconst MARKS: Readonly<Record<StatusState, string>> = { ok: \"OK \", fail: \"FAIL\", warn: \"WARN\", info: \"INFO\" };\n\n/**\n * This function makes a printer that writes to the streams of `options`. Each write puts a mark in place of each known\n * secret and of each shape of a token (`redactSecretShapes`), and ends with a new line.\n *\n * @param options - The streams and the known secrets.\n * @returns The printer.\n */\nexport function createPrinter(options: PrinterOptions): Printer {\n const { out, err = out, secrets = [] } = options;\n const write = (sink: TextSink, text: string): void => {\n sink.write(`${redactSecretShapes(secrets.length > 0 ? redactSecrets(text, secrets) : text)}\\n`);\n };\n return {\n line: (text = \"\") => write(out, text),\n table: (rows, table = {}) => {\n const { head, align = [], gap = \" \" } = table;\n const cells = [...(head ? [head] : []), ...rows].map((row) => row.map((cell) => String(cell ?? \"\")));\n const widths: number[] = [];\n for (const row of cells) row.forEach((cell, at) => (widths[at] = Math.max(widths[at] ?? 0, textLength(cell, \"grapheme\"))));\n for (const row of cells) {\n const parts = row.map((cell, at) => pad(cell, widths[at] ?? 0, { unit: \"grapheme\", side: align[at] === \"end\" ? \"start\" : \"end\" }));\n // A line has no spaces at its end, also after an empty last cell.\n write(out, parts.join(gap).trimEnd());\n }\n },\n status: (state, text) => write(state === \"fail\" ? err : out, `${MARKS[state]} ${text}`),\n warn: (text) => write(err, `warning: ${text}`),\n error: (error, context) => write(err, context === undefined ? errorMessage(error) : `${context}: ${errorMessage(error)}`),\n json: (value) => write(out, JSON.stringify(value, null, 2) ?? String(value)),\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA4DA,MAAM,QAA+C;CAAE,IAAI;CAAQ,MAAM;CAAQ,MAAM;CAAQ,MAAM;AAAO;;;;;;;;AAS5G,SAAgB,cAAc,SAAkC;CAC9D,MAAM,EAAE,KAAK,MAAM,KAAK,UAAU,CAAC,MAAM;CACzC,MAAM,SAAS,MAAgB,SAAuB;EACpD,KAAK,MAAM,GAAG,mBAAmB,QAAQ,SAAS,IAAI,cAAc,MAAM,OAAO,IAAI,IAAI,EAAE,GAAG;CAChG;CACA,OAAO;EACL,OAAO,OAAO,OAAO,MAAM,KAAK,IAAI;EACpC,QAAQ,MAAM,QAAQ,CAAC,MAAM;GAC3B,MAAM,EAAE,MAAM,QAAQ,CAAC,GAAG,MAAM,SAAS;GACzC,MAAM,QAAQ,CAAC,GAAI,OAAO,CAAC,IAAI,IAAI,CAAC,GAAI,GAAG,IAAI,CAAC,CAAC,KAAK,QAAQ,IAAI,KAAK,SAAS,OAAO,QAAQ,EAAE,CAAC,CAAC;GACnG,MAAM,SAAmB,CAAC;GAC1B,KAAK,MAAM,OAAO,OAAO,IAAI,SAAS,MAAM,OAAQ,OAAO,MAAM,KAAK,IAAI,OAAO,OAAO,GAAG,WAAW,MAAM,UAAU,CAAC,CAAE;GACzH,KAAK,MAAM,OAAO,OAAO;IACvB,MAAM,QAAQ,IAAI,KAAK,MAAM,OAAO,IAAI,MAAM,OAAO,OAAO,GAAG;KAAE,MAAM;KAAY,MAAM,MAAM,QAAQ,QAAQ,UAAU;IAAM,CAAC,CAAC;IAEjI,MAAM,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,QAAQ,CAAC;GACtC;EACF;EACA,SAAS,OAAO,SAAS,MAAM,UAAU,SAAS,MAAM,KAAK,GAAG,MAAM,OAAO,GAAG,MAAM;EACtF,OAAO,SAAS,MAAM,KAAK,YAAY,MAAM;EAC7C,QAAQ,OAAO,YAAY,MAAM,KAAK,YAAY,KAAA,IAAY,aAAa,KAAK,IAAI,GAAG,QAAQ,IAAI,aAAa,KAAK,GAAG;EACxH,OAAO,UAAU,MAAM,KAAK,KAAK,UAAU,OAAO,MAAM,CAAC,KAAK,OAAO,KAAK,CAAC;CAC7E;AACF"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/text",
|
|
4
|
-
"version": "0.0.
|
|
5
|
-
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens and of secrets by their context (findSecretShapes, redactSecretShapes, findSecretShapesInValue, CONTEXT_SHAPES, isSecretName), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf),
|
|
4
|
+
"version": "0.0.19",
|
|
5
|
+
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens and of secrets by their context (findSecretShapes, redactSecretShapes, findSecretShapesInValue, CONTEXT_SHAPES, isSecretName), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), a scan of HTML for its text and its start tags (scanHtml) with the decode of its character references (decodeReferences), and a printer of lines and tables to streams that the caller gives (createPrinter).",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"text",
|
|
8
8
|
"escape",
|
|
@@ -19,6 +19,9 @@
|
|
|
19
19
|
"pad",
|
|
20
20
|
"grapheme",
|
|
21
21
|
"unicode",
|
|
22
|
+
"cli",
|
|
23
|
+
"print",
|
|
24
|
+
"table",
|
|
22
25
|
"typescript"
|
|
23
26
|
],
|
|
24
27
|
"homepage": "https://github.com/mark1russell7/text#readme",
|
|
@@ -69,6 +72,10 @@
|
|
|
69
72
|
"types": "./build/english.d.ts",
|
|
70
73
|
"default": "./build/english.js"
|
|
71
74
|
},
|
|
75
|
+
"./passage": {
|
|
76
|
+
"types": "./build/passage.d.ts",
|
|
77
|
+
"default": "./build/passage.js"
|
|
78
|
+
},
|
|
72
79
|
"./search": {
|
|
73
80
|
"types": "./build/search.d.ts",
|
|
74
81
|
"default": "./build/search.js"
|
|
@@ -77,6 +84,10 @@
|
|
|
77
84
|
"types": "./build/shell.d.ts",
|
|
78
85
|
"default": "./build/shell.js"
|
|
79
86
|
},
|
|
87
|
+
"./print": {
|
|
88
|
+
"types": "./build/print.d.ts",
|
|
89
|
+
"default": "./build/print.js"
|
|
90
|
+
},
|
|
80
91
|
"./package.json": "./package.json"
|
|
81
92
|
},
|
|
82
93
|
"files": [
|
package/src/passage.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module finds a passage in a text, for example a quote in the text of its source. The key of a text
|
|
3
|
+
* (`passageKey`) makes the case, the quote marks, the dashes and the white space not significant. `findPassage` gives
|
|
4
|
+
* the span of the passage in the text. Each function has no I/O.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { searchKey } from "./search.ts";
|
|
8
|
+
|
|
9
|
+
/** The quote marks that `passageKey` changes to the apostrophe: the single quotes, the low and the reversed single quotes, and the prime. */
|
|
10
|
+
const SINGLE_QUOTES = /[\u2018\u2019\u201A\u201B\u2032\u02BC]/gu;
|
|
11
|
+
/** The quote marks that `passageKey` changes to the double quote: the double quotes, the low and the reversed double quotes and the guillemets. NFKC changes a double prime to two primes. */
|
|
12
|
+
const DOUBLE_QUOTES = /[\u201C\u201D\u201E\u201F\u00AB\u00BB]/gu;
|
|
13
|
+
/** The dashes that `passageKey` changes to the hyphen-minus. They are the hyphen, the non-breaking hyphen, the figure dash, the en dash and the em dash, the bar and the minus sign. */
|
|
14
|
+
const DASHES = /[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/gu;
|
|
15
|
+
/** The characters with no width that `passageKey` removes: the soft hyphen, the zero-width space, the joiners and the byte order mark. */
|
|
16
|
+
const NO_WIDTH = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/gu;
|
|
17
|
+
/** A grapheme of white space only. */
|
|
18
|
+
const SPACE = /^\s+$/u;
|
|
19
|
+
|
|
20
|
+
/** The grapheme segmenter of `passageKey` and `findPassage`. The module makes it one time, at the first use. */
|
|
21
|
+
let graphemeSegmenter: Intl.Segmenter | undefined;
|
|
22
|
+
|
|
23
|
+
/** The key of a text for a passage search, with the start and the end in the text of each code unit of the key. */
|
|
24
|
+
interface PassageParts {
|
|
25
|
+
readonly key: string;
|
|
26
|
+
readonly starts: readonly number[];
|
|
27
|
+
readonly ends: readonly number[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** This function gives the key of a text and the place of each code unit of the key in the text. */
|
|
31
|
+
function passageParts(text: string): PassageParts {
|
|
32
|
+
graphemeSegmenter ??= new Intl.Segmenter("en", { granularity: "grapheme" });
|
|
33
|
+
let key = "";
|
|
34
|
+
const starts: number[] = [];
|
|
35
|
+
const ends: number[] = [];
|
|
36
|
+
for (const { segment, index } of graphemeSegmenter.segment(text)) {
|
|
37
|
+
// A joiner is a part of the grapheme before it, so the test of white space comes after the removal.
|
|
38
|
+
const clean = segment.replace(NO_WIDTH, "");
|
|
39
|
+
let part: string;
|
|
40
|
+
if (clean === "") part = "";
|
|
41
|
+
else if (SPACE.test(clean)) part = key === "" || key.endsWith(" ") ? "" : " ";
|
|
42
|
+
else part = searchKey(clean).replace(SINGLE_QUOTES, "'").replace(DOUBLE_QUOTES, '"').replace(DASHES, "-");
|
|
43
|
+
for (let unit = 0; unit < part.length; unit++) {
|
|
44
|
+
starts.push(index);
|
|
45
|
+
ends.push(index + segment.length);
|
|
46
|
+
}
|
|
47
|
+
key += part;
|
|
48
|
+
}
|
|
49
|
+
if (key.endsWith(" ")) return { key: key.slice(0, -1), starts: starts.slice(0, -1), ends: ends.slice(0, -1) };
|
|
50
|
+
return { key, starts, ends };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* This function gives the key of a text for a passage search. `findPassage` compares the keys of two texts. The function
|
|
55
|
+
* does these steps on each grapheme of the text:
|
|
56
|
+
*
|
|
57
|
+
* 1. It removes the characters with no width: the soft hyphen, the zero-width space, the joiners and the byte order mark.
|
|
58
|
+
* 2. It applies `searchKey`. Thus the case of the letters and the NFKC forms are not significant.
|
|
59
|
+
* 3. It changes each curly or low quote mark and each prime to the apostrophe or to the double quote. It changes each dash and the minus sign to the hyphen-minus.
|
|
60
|
+
* 4. It changes each run of white space to one space, and it removes the white space at the start and at the end.
|
|
61
|
+
*
|
|
62
|
+
* Accents and punctuation stay. A hyphen at the end of a line stays, because the function cannot tell it from a real hyphen.
|
|
63
|
+
*
|
|
64
|
+
* @param text - The plain text.
|
|
65
|
+
* @returns The key of the text.
|
|
66
|
+
*/
|
|
67
|
+
export function passageKey(text: string): string {
|
|
68
|
+
return passageParts(text).key;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The place of a passage in a text, in UTF-16 code units. The passage is `text.slice(start, end)`. */
|
|
72
|
+
export interface PassageSpan {
|
|
73
|
+
readonly start: number;
|
|
74
|
+
readonly end: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* This function finds a passage in a text, for example a quote in the text of its source. It has no I/O.
|
|
79
|
+
*
|
|
80
|
+
* - The text holds the passage when the key of the text (`passageKey`) contains the key of the passage.
|
|
81
|
+
* - The result is the first place, from the start of the first grapheme to the end of the last grapheme of the match.
|
|
82
|
+
* - A passage can start or end inside a word, as in `wordSearch`. The caller tests the edges when a word must be whole.
|
|
83
|
+
* - A passage with an empty key, for example only white space, gives `undefined`. It is not a match at 0.
|
|
84
|
+
*
|
|
85
|
+
* @param text - The text to search, for example the text of a source.
|
|
86
|
+
* @param passage - The passage, for example a quote.
|
|
87
|
+
* @returns The span of the passage in the text, or `undefined` when the text does not hold it.
|
|
88
|
+
*/
|
|
89
|
+
export function findPassage(text: string, passage: string): PassageSpan | undefined {
|
|
90
|
+
const needle = passageKey(passage);
|
|
91
|
+
if (needle === "") return undefined;
|
|
92
|
+
const parts = passageParts(text);
|
|
93
|
+
const at = parts.key.indexOf(needle);
|
|
94
|
+
if (at < 0) return undefined;
|
|
95
|
+
return { start: parts.starts[at] ?? 0, end: parts.ends[at + needle.length - 1] ?? 0 };
|
|
96
|
+
}
|
package/src/print.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The entry `@mark1russell7/text/print`: the printer of the output of a command-line tool for a person. It writes lines,
|
|
3
|
+
* tables, status lines and the text of a thrown value to streams that the caller gives. Thus the entry imports no `node:`
|
|
4
|
+
* module, and a test gives a buffer in place of a stream.
|
|
5
|
+
*
|
|
6
|
+
* The printer is for output that a person reads: the text, the tables and the status lines of a CLI. A diagnostic of a
|
|
7
|
+
* library or a service (a warning, a debug line, a caught error) is not output. It goes to a log record with its trace
|
|
8
|
+
* context, through the logger of OpenTelemetry, and not to a printer.
|
|
9
|
+
*/
|
|
10
|
+
import { errorMessage } from "./error.ts";
|
|
11
|
+
import { pad, textLength } from "./length.ts";
|
|
12
|
+
import { redactSecretShapes, redactSecrets, type Secret } from "./redact.ts";
|
|
13
|
+
|
|
14
|
+
/** A stream of text, for example `process.stdout`. The printer uses only its `write`. */
|
|
15
|
+
export interface TextSink {
|
|
16
|
+
write(text: string): unknown;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The options of `createPrinter`. */
|
|
20
|
+
export interface PrinterOptions {
|
|
21
|
+
/** The stream of the output, for example `process.stdout`. */
|
|
22
|
+
readonly out: TextSink;
|
|
23
|
+
/** The stream of the errors and warnings, for example `process.stderr`. The default is `out`. */
|
|
24
|
+
readonly err?: TextSink;
|
|
25
|
+
/** The known secrets, for example the tokens of the command. The printer puts a mark in place of each before a write. */
|
|
26
|
+
readonly secrets?: readonly Secret[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The side of a column of a table. `end` aligns the cells at the right, for numbers. */
|
|
30
|
+
export type ColumnAlign = "start" | "end";
|
|
31
|
+
|
|
32
|
+
/** The options of `Printer.table`. */
|
|
33
|
+
export interface TableOptions {
|
|
34
|
+
/** The head of each column. The printer writes it as the first row. */
|
|
35
|
+
readonly head?: readonly string[];
|
|
36
|
+
/** The side of each column. The default is `start` for each column. */
|
|
37
|
+
readonly align?: readonly ColumnAlign[];
|
|
38
|
+
/** The text between two columns. The default is two spaces. */
|
|
39
|
+
readonly gap?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The state of a status line. */
|
|
43
|
+
export type StatusState = "ok" | "fail" | "warn" | "info";
|
|
44
|
+
|
|
45
|
+
/** A printer of the output of a command-line tool. */
|
|
46
|
+
export interface Printer {
|
|
47
|
+
/** This function writes a line to `out`. No text gives an empty line. */
|
|
48
|
+
line(text?: string): void;
|
|
49
|
+
/** This function writes a table to `out`. A cell is any value, and `String` gives its text. */
|
|
50
|
+
table(rows: readonly (readonly unknown[])[], options?: TableOptions): void;
|
|
51
|
+
/** This function writes a status line to `out`, for example `FAIL build: 2 errors`. The state `fail` goes to `err`. */
|
|
52
|
+
status(state: StatusState, text: string): void;
|
|
53
|
+
/** This function writes a warning line to `err`. */
|
|
54
|
+
warn(text: string): void;
|
|
55
|
+
/** This function writes the text of a thrown value to `err`. It does not throw. A `context` comes before the text. */
|
|
56
|
+
error(error: unknown, context?: string): void;
|
|
57
|
+
/** This function writes a value as JSON with two spaces, to `out`. It throws as `JSON.stringify` does, for a bigint or a cycle. */
|
|
58
|
+
json(value: unknown): void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const MARKS: Readonly<Record<StatusState, string>> = { ok: "OK ", fail: "FAIL", warn: "WARN", info: "INFO" };
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* This function makes a printer that writes to the streams of `options`. Each write puts a mark in place of each known
|
|
65
|
+
* secret and of each shape of a token (`redactSecretShapes`), and ends with a new line.
|
|
66
|
+
*
|
|
67
|
+
* @param options - The streams and the known secrets.
|
|
68
|
+
* @returns The printer.
|
|
69
|
+
*/
|
|
70
|
+
export function createPrinter(options: PrinterOptions): Printer {
|
|
71
|
+
const { out, err = out, secrets = [] } = options;
|
|
72
|
+
const write = (sink: TextSink, text: string): void => {
|
|
73
|
+
sink.write(`${redactSecretShapes(secrets.length > 0 ? redactSecrets(text, secrets) : text)}\n`);
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
line: (text = "") => write(out, text),
|
|
77
|
+
table: (rows, table = {}) => {
|
|
78
|
+
const { head, align = [], gap = " " } = table;
|
|
79
|
+
const cells = [...(head ? [head] : []), ...rows].map((row) => row.map((cell) => String(cell ?? "")));
|
|
80
|
+
const widths: number[] = [];
|
|
81
|
+
for (const row of cells) row.forEach((cell, at) => (widths[at] = Math.max(widths[at] ?? 0, textLength(cell, "grapheme"))));
|
|
82
|
+
for (const row of cells) {
|
|
83
|
+
const parts = row.map((cell, at) => pad(cell, widths[at] ?? 0, { unit: "grapheme", side: align[at] === "end" ? "start" : "end" }));
|
|
84
|
+
// A line has no spaces at its end, also after an empty last cell.
|
|
85
|
+
write(out, parts.join(gap).trimEnd());
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
status: (state, text) => write(state === "fail" ? err : out, `${MARKS[state]} ${text}`),
|
|
89
|
+
warn: (text) => write(err, `warning: ${text}`),
|
|
90
|
+
error: (error, context) => write(err, context === undefined ? errorMessage(error) : `${context}: ${errorMessage(error)}`),
|
|
91
|
+
json: (value) => write(out, JSON.stringify(value, null, 2) ?? String(value)),
|
|
92
|
+
};
|
|
93
|
+
}
|
package/build/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF"}
|