@mark1russell7/text 0.0.2 → 0.0.4

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @mark1russell7/text
2
2
 
3
- Plain text helpers. The first group is the escapes of a text for five targets.
3
+ Plain text helpers in four groups. The groups are the escapes of a text for five targets, the English word forms, a word search and the removal of secrets.
4
4
 
5
5
  ```sh
6
6
  pnpm add @mark1russell7/text
@@ -26,6 +26,60 @@ next")}`); // "::warning title=a%3A b::50%25%0Anext"
26
26
  escapeMarkdown("a | b *c*"); // "a \\| b \\*c\\*"
27
27
  ```
28
28
 
29
+ ## English word forms
30
+
31
+ `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.
32
+
33
+ ```ts
34
+ import { countOf } from "@mark1russell7/text";
35
+
36
+ countOf(1, "site"); // "1 site"
37
+ countOf(1024, "site"); // "1,024 sites"
38
+ countOf(3, "match", "matches"); // "3 matches"
39
+ ```
40
+
41
+ ## A word search
42
+
43
+ `wordSearch(query)` gives a test of a text. A text agrees when it has each word of the search, in any order and in any case. A word can be a part of a longer word.
44
+
45
+ `searchKey(text)` gives the form that the test compares. It applies NFKC, then the lower case, the upper case and the lower case again. Then it changes the final sigma "ς" to "σ". It uses no rules of a locale.
46
+
47
+ ```ts
48
+ import { searchKey, wordSearch } from "@mark1russell7/text";
49
+
50
+ wordSearch("news WORLD")("World News Today"); // true
51
+ wordSearch("strasse")("Hauptstraße 1"); // true
52
+ wordSearch("istanbul")("İSTANBUL"); // false: "İ" keeps its dot as U+0307
53
+ searchKey("file"); // "file"
54
+ ```
55
+
56
+ ## The removal of secrets
57
+
58
+ `redactSecrets(text, secrets, options?)` puts a mark in place of each secret in a text. Use it on an error message or a log line before it goes out. The function is in the entry `@mark1russell7/text/redact`, so the root entry stays small.
59
+
60
+ A secret goes into a text in more than one form. The function removes each of these forms:
61
+
62
+ | Form | Example of the secret `k/y!` | Where it goes |
63
+ | --- | --- | --- |
64
+ | The raw form | `k/y!` | A header, a body, a message |
65
+ | The form of `encodeURIComponent` | `k%2Fy!` | The path or the query of a URL |
66
+ | The form of `URLSearchParams` | `k%2Fy%21` | A query, or the body of an HTML form |
67
+ | The Base64 form of `user:password` | `dXNlcjprL3kh` | The value of an `Authorization: Basic` header |
68
+
69
+ A `Secret` is a string, or a pair `{ user, password }` for HTTP Basic. For a pair, the function removes the password and the Base64 form of the pair. The user stays, because a user name is not a secret. `RedactOptions` has `mark`, the text in place of each secret. The default mark is `[secret]`.
70
+
71
+ ```ts
72
+ import { redactSecrets, type RedactOptions, type Secret } from "@mark1russell7/text/redact";
73
+
74
+ const secrets: Secret[] = ["k/y!", { user: "user", password: "k/y!" }];
75
+ redactSecrets("GET /v1/items?apiKey=k%2Fy!", secrets); // "GET /v1/items?apiKey=[secret]"
76
+ redactSecrets("Authorization: Basic dXNlcjprL3kh", secrets); // "Authorization: Basic [secret]"
77
+ const options: RedactOptions = { mark: "***" };
78
+ redactSecrets("token=k/y!", secrets, options); // "token=***"
79
+ ```
80
+
81
+ The function examines the text one time. At each position, it removes the longest form that agrees, so a secret in a secret gives one mark. It ignores an empty secret.
82
+
29
83
  ## The copies that this package replaces
30
84
 
31
85
  The tests run 58 copies of these functions from other repositories of the owner. Each copy comes from a list of the duplication atlas, at a pinned commit. The file `test/copies.json` has each copy, and `test/differences.ts` has each difference from the function of this package, with its reason. A copy that is not in the list gives the same output on each of the 1000 test strings.
@@ -35,3 +89,6 @@ The tests run 58 copies of these functions from other repositories of the owner.
35
89
  - `escapeHtml` does not escape quotes. For an attribute value, use `escapeAttribute`.
36
90
  - `escapeRegExp` gives a pattern for use outside a character class. In a class, `-` also has a meaning.
37
91
  - `escapeMarkdown` does not change spaces. Four spaces at the start of a line make a code block.
92
+ - `wordSearch` keeps accents, so "cafe" does not find "café".
93
+ - `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
94
+ - `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,83 @@
1
+ // src/escape.ts
2
+ /**
3
+ * This module has the escapes of plain text for five targets. The targets are HTML content, an HTML attribute, a
4
+ * regular expression, one line of Markdown and a GitHub Actions workflow command. Each function changes only the characters that have a meaning in its target.
5
+ */
6
+ const HTML = {
7
+ "&": "&",
8
+ "<": "&lt;",
9
+ ">": "&gt;"
10
+ };
11
+ const ATTRIBUTE = {
12
+ ...HTML,
13
+ "\"": "&quot;",
14
+ "'": "&#39;"
15
+ };
16
+ /**
17
+ * This function escapes a text for the content of an HTML element. It changes `&`, `<` and `>` to named character
18
+ * references. The quotes stay, because they have no meaning in element content.
19
+ *
20
+ * @param text - The plain text.
21
+ * @returns The text with `&amp;`, `&lt;` and `&gt;` in place of the three characters.
22
+ */
23
+ function escapeHtml(text) {
24
+ return text.replace(/[&<>]/g, (char) => HTML[char] ?? char);
25
+ }
26
+ /**
27
+ * This function escapes a text for an HTML attribute value in double quotes or in single quotes. It changes `&`, `<`,
28
+ * `>`, `"` and `'`. The result is also correct in element content.
29
+ *
30
+ * @param text - The plain text.
31
+ * @returns The text with `&amp;`, `&lt;`, `&gt;`, `&quot;` and `&#39;` in place of the five characters.
32
+ */
33
+ function escapeAttribute(text) {
34
+ return text.replace(/[&<>"']/g, (char) => ATTRIBUTE[char] ?? char);
35
+ }
36
+ /**
37
+ * This function escapes a text for the pattern of a regular expression, outside a character class. It puts a backslash
38
+ * before each syntax character of ECMAScript: `^ $ \ . * + ? ( ) [ ] { } |`. The pattern matches only the text, with
39
+ * the flag `u`, with the flag `v` and with no flag.
40
+ *
41
+ * @param text - The plain text.
42
+ * @returns A pattern for `new RegExp` that matches the text.
43
+ */
44
+ function escapeRegExp(text) {
45
+ return text.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
46
+ }
47
+ /**
48
+ * This function escapes a text for one line of CommonMark or GitHub Markdown: a paragraph, a heading or a table cell.
49
+ * It puts a backslash before each ASCII punctuation character, and changes each line end to a space.
50
+ *
51
+ * A backslash before an ASCII punctuation character always gives the character itself. Thus no character of the result
52
+ * starts emphasis, code, a link, HTML, an entity, a list or a table column. Four spaces at the start of a line still
53
+ * make a code block.
54
+ *
55
+ * @param text - The plain text.
56
+ * @returns The text for one line of Markdown.
57
+ */
58
+ function escapeMarkdown(text) {
59
+ return text.replace(/\r\n?|\n/g, " ").replace(/[!-/:-@[-`{-~]/g, "\\$&");
60
+ }
61
+ /**
62
+ * This function escapes a text for the data of a GitHub Actions workflow command, the part after `::`. It changes `%`,
63
+ * the carriage return and the line feed to `%25`, `%0D` and `%0A`, so the command stays on one line.
64
+ *
65
+ * @param text - The plain text.
66
+ * @returns The data of the command. The runner decodes it to the text.
67
+ */
68
+ function escapeWorkflowData(text) {
69
+ return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
70
+ }
71
+ /**
72
+ * This function escapes a text for a property value of a GitHub Actions workflow command, for example `title=`. It
73
+ * changes the characters of `escapeWorkflowData`, and also `:` and `,` to `%3A` and `%2C`.
74
+ *
75
+ * @param text - The plain text.
76
+ * @returns The property value. The runner decodes it to the text.
77
+ */
78
+ function escapeWorkflowProperty(text) {
79
+ return escapeWorkflowData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
80
+ }
81
+ export { escapeWorkflowData as a, escapeRegExp as i, escapeHtml as n, escapeWorkflowProperty as o, escapeMarkdown as r, escapeAttribute as t };
82
+
83
+ //# sourceMappingURL=escape-vfOeIxac.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escape-vfOeIxac.js","names":[],"sources":["../src/escape.ts"],"sourcesContent":["/**\n * This module has the escapes of plain text for five targets. The targets are HTML content, an HTML attribute, a\n * regular expression, one line of Markdown and a GitHub Actions workflow command. Each function changes only the characters that have a meaning in its target.\n */\n\nconst HTML: Readonly<Record<string, string>> = { \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\" };\nconst ATTRIBUTE: Readonly<Record<string, string>> = { ...HTML, '\"': \"&quot;\", \"'\": \"&#39;\" };\n\n/**\n * This function escapes a text for the content of an HTML element. It changes `&`, `<` and `>` to named character\n * references. The quotes stay, because they have no meaning in element content.\n *\n * @param text - The plain text.\n * @returns The text with `&amp;`, `&lt;` and `&gt;` in place of the three characters.\n */\nexport function escapeHtml(text: string): string {\n return text.replace(/[&<>]/g, (char) => HTML[char] ?? char);\n}\n\n/**\n * This function escapes a text for an HTML attribute value in double quotes or in single quotes. It changes `&`, `<`,\n * `>`, `\"` and `'`. The result is also correct in element content.\n *\n * @param text - The plain text.\n * @returns The text with `&amp;`, `&lt;`, `&gt;`, `&quot;` and `&#39;` in place of the five characters.\n */\nexport function escapeAttribute(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => ATTRIBUTE[char] ?? char);\n}\n\n/**\n * This function escapes a text for the pattern of a regular expression, outside a character class. It puts a backslash\n * before each syntax character of ECMAScript: `^ $ \\ . * + ? ( ) [ ] { } |`. The pattern matches only the text, with\n * the flag `u`, with the flag `v` and with no flag.\n *\n * @param text - The plain text.\n * @returns A pattern for `new RegExp` that matches the text.\n */\nexport function escapeRegExp(text: string): string {\n return text.replace(/[\\\\^$.*+?()[\\]{}|]/g, \"\\\\$&\");\n}\n\n/**\n * This function escapes a text for one line of CommonMark or GitHub Markdown: a paragraph, a heading or a table cell.\n * It puts a backslash before each ASCII punctuation character, and changes each line end to a space.\n *\n * A backslash before an ASCII punctuation character always gives the character itself. Thus no character of the result\n * starts emphasis, code, a link, HTML, an entity, a list or a table column. Four spaces at the start of a line still\n * make a code block.\n *\n * @param text - The plain text.\n * @returns The text for one line of Markdown.\n */\nexport function escapeMarkdown(text: string): string {\n return text.replace(/\\r\\n?|\\n/g, \" \").replace(/[!-/:-@[-`{-~]/g, \"\\\\$&\");\n}\n\n/**\n * This function escapes a text for the data of a GitHub Actions workflow command, the part after `::`. It changes `%`,\n * the carriage return and the line feed to `%25`, `%0D` and `%0A`, so the command stays on one line.\n *\n * @param text - The plain text.\n * @returns The data of the command. The runner decodes it to the text.\n */\nexport function escapeWorkflowData(text: string): string {\n return text.replaceAll(\"%\", \"%25\").replaceAll(\"\\r\", \"%0D\").replaceAll(\"\\n\", \"%0A\");\n}\n\n/**\n * This function escapes a text for a property value of a GitHub Actions workflow command, for example `title=`. It\n * changes the characters of `escapeWorkflowData`, and also `:` and `,` to `%3A` and `%2C`.\n *\n * @param text - The plain text.\n * @returns The property value. The runner decodes it to the text.\n */\nexport function escapeWorkflowProperty(text: string): string {\n return escapeWorkflowData(text).replaceAll(\":\", \"%3A\").replaceAll(\",\", \"%2C\");\n}\n"],"mappings":";;;;;AAKA,MAAM,OAAyC;CAAE,KAAK;CAAS,KAAK;CAAQ,KAAK;AAAO;AACxF,MAAM,YAA8C;CAAE,GAAG;CAAM,MAAK;CAAU,KAAK;AAAQ;;;;;;;;AAS3F,SAAgB,WAAW,MAAsB;CAC/C,OAAO,KAAK,QAAQ,WAAW,SAAS,KAAK,SAAS,IAAI;AAC5D;;;;;;;;AASA,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,KAAK,QAAQ,aAAa,SAAS,UAAU,SAAS,IAAI;AACnE;;;;;;;;;AAUA,SAAgB,aAAa,MAAsB;CACjD,OAAO,KAAK,QAAQ,uBAAuB,MAAM;AACnD;;;;;;;;;;;;AAaA,SAAgB,eAAe,MAAsB;CACnD,OAAO,KAAK,QAAQ,aAAa,GAAG,CAAC,CAAC,QAAQ,mBAAmB,MAAM;AACzE;;;;;;;;AASA,SAAgB,mBAAmB,MAAsB;CACvD,OAAO,KAAK,WAAW,KAAK,KAAK,CAAC,CAAC,WAAW,MAAM,KAAK,CAAC,CAAC,WAAW,MAAM,KAAK;AACnF;;;;;;;;AASA,SAAgB,uBAAuB,MAAsB;CAC3D,OAAO,mBAAmB,IAAI,CAAC,CAAC,WAAW,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,KAAK;AAC9E"}
package/build/index.d.ts CHANGED
@@ -1,7 +1,22 @@
1
1
  /**
2
- * The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes,
3
- * regular expressions, Markdown and GitHub Actions workflow commands.
2
+ * The entry of `@mark1russell7/text`: plain text helpers. The groups are the escapes for HTML, attributes, regular
3
+ * expressions, Markdown and GitHub Actions workflow commands, the English word forms and a word search. The entry
4
+ * `@mark1russell7/text/redact` removes secrets from a text.
4
5
  */
6
+ /**
7
+ * This module has the English word forms.
8
+ */
9
+ /**
10
+ * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
11
+ * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
12
+ * three decimal places.
13
+ *
14
+ * @param count - The number of things.
15
+ * @param noun - The singular noun.
16
+ * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
17
+ * @returns The count, a space and the noun.
18
+ */
19
+ export declare function countOf(count: number, noun: string, plural?: string): string;
5
20
  /**
6
21
  * This function escapes a text for the content of an HTML element. It changes `&`, `<` and `>` to named character
7
22
  * references. The quotes stay, because they have no meaning in element content.
@@ -55,4 +70,32 @@ export declare function escapeWorkflowData(text: string): string;
55
70
  * @returns The property value. The runner decodes it to the text.
56
71
  */
57
72
  export declare function escapeWorkflowProperty(text: string): string;
73
+ /**
74
+ * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
75
+ *
76
+ * 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
77
+ * with ASCII letters.
78
+ * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
79
+ * "ss".
80
+ * 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
81
+ * 4. It applies NFKC again.
82
+ *
83
+ * The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
84
+ * Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
85
+ *
86
+ * @param text - The plain text.
87
+ * @returns The search key of the text.
88
+ */
89
+ export declare function searchKey(text: string): string;
90
+ /**
91
+ * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
92
+ * the key into words at each run of white space, the class `\s` of a regular expression.
93
+ *
94
+ * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
95
+ * search "art" finds "Party". A search with no words agrees with each text.
96
+ *
97
+ * @param query - The search, as a person types it.
98
+ * @returns The test of a text.
99
+ */
100
+ export declare function wordSearch(query: string): (text: string) => boolean;
58
101
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/escape.ts"],"mappings":";;;;;;;;;;;wBAegB,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/english.ts","../src/escape.ts","../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;;;wBAcgB,QAAQ,eAAe,cAAc;;;;;;;;wBCCrC,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB;;;;;;;;;;;;;;;;;wBCnDvB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB"}
package/build/index.js CHANGED
@@ -1,83 +1,61 @@
1
- // src/escape.ts
1
+ import { a as escapeWorkflowData, i as escapeRegExp, n as escapeHtml, o as escapeWorkflowProperty, r as escapeMarkdown, t as escapeAttribute } from "./escape-vfOeIxac.js";
2
+ // src/english.ts
2
3
  /**
3
- * This module has the escapes of plain text for five targets. The targets are HTML content, an HTML attribute, a
4
- * regular expression, one line of Markdown and a GitHub Actions workflow command. Each function changes only the characters that have a meaning in its target.
4
+ * This module has the English word forms.
5
5
  */
6
- const HTML = {
7
- "&": "&amp;",
8
- "<": "&lt;",
9
- ">": "&gt;"
10
- };
11
- const ATTRIBUTE = {
12
- ...HTML,
13
- "\"": "&quot;",
14
- "'": "&#39;"
15
- };
16
6
  /**
17
- * This function escapes a text for the content of an HTML element. It changes `&`, `<` and `>` to named character
18
- * references. The quotes stay, because they have no meaning in element content.
7
+ * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
8
+ * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
9
+ * three decimal places.
19
10
  *
20
- * @param text - The plain text.
21
- * @returns The text with `&amp;`, `&lt;` and `&gt;` in place of the three characters.
11
+ * @param count - The number of things.
12
+ * @param noun - The singular noun.
13
+ * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
14
+ * @returns The count, a space and the noun.
22
15
  */
23
- function escapeHtml(text) {
24
- return text.replace(/[&<>]/g, (char) => HTML[char] ?? char);
16
+ function countOf(count, noun, plural = `${noun}s`) {
17
+ return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
25
18
  }
19
+ // src/search.ts
26
20
  /**
27
- * This function escapes a text for an HTML attribute value in double quotes or in single quotes. It changes `&`, `<`,
28
- * `>`, `"` and `'`. The result is also correct in element content.
29
- *
30
- * @param text - The plain text.
31
- * @returns The text with `&amp;`, `&lt;`, `&gt;`, `&quot;` and `&#39;` in place of the five characters.
21
+ * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,
22
+ * in any order. The case of the letters is not significant.
32
23
  */
33
- function escapeAttribute(text) {
34
- return text.replace(/[&<>"']/g, (char) => ATTRIBUTE[char] ?? char);
35
- }
24
+ /** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
25
+ const FINAL_SIGMA = /ς/gu;
36
26
  /**
37
- * This function escapes a text for the pattern of a regular expression, outside a character class. It puts a backslash
38
- * before each syntax character of ECMAScript: `^ $ \ . * + ? ( ) [ ] { } |`. The pattern matches only the text, with
39
- * the flag `u`, with the flag `v` and with no flag.
27
+ * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
40
28
  *
41
- * @param text - The plain text.
42
- * @returns A pattern for `new RegExp` that matches the text.
43
- */
44
- function escapeRegExp(text) {
45
- return text.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
46
- }
47
- /**
48
- * This function escapes a text for one line of CommonMark or GitHub Markdown: a paragraph, a heading or a table cell.
49
- * It puts a backslash before each ASCII punctuation character, and changes each line end to a space.
29
+ * 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
30
+ * with ASCII letters.
31
+ * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
32
+ * "ss".
33
+ * 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
34
+ * 4. It applies NFKC again.
50
35
  *
51
- * A backslash before an ASCII punctuation character always gives the character itself. Thus no character of the result
52
- * starts emphasis, code, a link, HTML, an entity, a list or a table column. Four spaces at the start of a line still
53
- * make a code block.
36
+ * The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
37
+ * Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
54
38
  *
55
39
  * @param text - The plain text.
56
- * @returns The text for one line of Markdown.
40
+ * @returns The search key of the text.
57
41
  */
58
- function escapeMarkdown(text) {
59
- return text.replace(/\r\n?|\n/g, " ").replace(/[!-/:-@[-`{-~]/g, "\\$&");
42
+ function searchKey(text) {
43
+ return text.normalize("NFKC").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, "σ").normalize("NFKC");
60
44
  }
61
45
  /**
62
- * This function escapes a text for the data of a GitHub Actions workflow command, the part after `::`. It changes `%`,
63
- * the carriage return and the line feed to `%25`, `%0D` and `%0A`, so the command stays on one line.
46
+ * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
47
+ * the key into words at each run of white space, the class `\s` of a regular expression.
64
48
  *
65
- * @param text - The plain text.
66
- * @returns The data of the command. The runner decodes it to the text.
67
- */
68
- function escapeWorkflowData(text) {
69
- return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
70
- }
71
- /**
72
- * This function escapes a text for a property value of a GitHub Actions workflow command, for example `title=`. It
73
- * changes the characters of `escapeWorkflowData`, and also `:` and `,` to `%3A` and `%2C`.
49
+ * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
50
+ * search "art" finds "Party". A search with no words agrees with each text.
74
51
  *
75
- * @param text - The plain text.
76
- * @returns The property value. The runner decodes it to the text.
52
+ * @param query - The search, as a person types it.
53
+ * @returns The test of a text.
77
54
  */
78
- function escapeWorkflowProperty(text) {
79
- return escapeWorkflowData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
55
+ function wordSearch(query) {
56
+ const words = searchKey(query).split(/\s+/u).filter((word) => word !== "");
57
+ return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));
80
58
  }
81
- export { escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty };
59
+ export { countOf, escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty, searchKey, wordSearch };
82
60
 
83
61
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/escape.ts"],"sourcesContent":["/**\n * This module has the escapes of plain text for five targets. The targets are HTML content, an HTML attribute, a\n * regular expression, one line of Markdown and a GitHub Actions workflow command. Each function changes only the characters that have a meaning in its target.\n */\n\nconst HTML: Readonly<Record<string, string>> = { \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\" };\nconst ATTRIBUTE: Readonly<Record<string, string>> = { ...HTML, '\"': \"&quot;\", \"'\": \"&#39;\" };\n\n/**\n * This function escapes a text for the content of an HTML element. It changes `&`, `<` and `>` to named character\n * references. The quotes stay, because they have no meaning in element content.\n *\n * @param text - The plain text.\n * @returns The text with `&amp;`, `&lt;` and `&gt;` in place of the three characters.\n */\nexport function escapeHtml(text: string): string {\n return text.replace(/[&<>]/g, (char) => HTML[char] ?? char);\n}\n\n/**\n * This function escapes a text for an HTML attribute value in double quotes or in single quotes. It changes `&`, `<`,\n * `>`, `\"` and `'`. The result is also correct in element content.\n *\n * @param text - The plain text.\n * @returns The text with `&amp;`, `&lt;`, `&gt;`, `&quot;` and `&#39;` in place of the five characters.\n */\nexport function escapeAttribute(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => ATTRIBUTE[char] ?? char);\n}\n\n/**\n * This function escapes a text for the pattern of a regular expression, outside a character class. It puts a backslash\n * before each syntax character of ECMAScript: `^ $ \\ . * + ? ( ) [ ] { } |`. The pattern matches only the text, with\n * the flag `u`, with the flag `v` and with no flag.\n *\n * @param text - The plain text.\n * @returns A pattern for `new RegExp` that matches the text.\n */\nexport function escapeRegExp(text: string): string {\n return text.replace(/[\\\\^$.*+?()[\\]{}|]/g, \"\\\\$&\");\n}\n\n/**\n * This function escapes a text for one line of CommonMark or GitHub Markdown: a paragraph, a heading or a table cell.\n * It puts a backslash before each ASCII punctuation character, and changes each line end to a space.\n *\n * A backslash before an ASCII punctuation character always gives the character itself. Thus no character of the result\n * starts emphasis, code, a link, HTML, an entity, a list or a table column. Four spaces at the start of a line still\n * make a code block.\n *\n * @param text - The plain text.\n * @returns The text for one line of Markdown.\n */\nexport function escapeMarkdown(text: string): string {\n return text.replace(/\\r\\n?|\\n/g, \" \").replace(/[!-/:-@[-`{-~]/g, \"\\\\$&\");\n}\n\n/**\n * This function escapes a text for the data of a GitHub Actions workflow command, the part after `::`. It changes `%`,\n * the carriage return and the line feed to `%25`, `%0D` and `%0A`, so the command stays on one line.\n *\n * @param text - The plain text.\n * @returns The data of the command. The runner decodes it to the text.\n */\nexport function escapeWorkflowData(text: string): string {\n return text.replaceAll(\"%\", \"%25\").replaceAll(\"\\r\", \"%0D\").replaceAll(\"\\n\", \"%0A\");\n}\n\n/**\n * This function escapes a text for a property value of a GitHub Actions workflow command, for example `title=`. It\n * changes the characters of `escapeWorkflowData`, and also `:` and `,` to `%3A` and `%2C`.\n *\n * @param text - The plain text.\n * @returns The property value. The runner decodes it to the text.\n */\nexport function escapeWorkflowProperty(text: string): string {\n return escapeWorkflowData(text).replaceAll(\":\", \"%3A\").replaceAll(\",\", \"%2C\");\n}\n"],"mappings":";;;;;AAKA,MAAM,OAAyC;CAAE,KAAK;CAAS,KAAK;CAAQ,KAAK;AAAO;AACxF,MAAM,YAA8C;CAAE,GAAG;CAAM,MAAK;CAAU,KAAK;AAAQ;;;;;;;;AAS3F,SAAgB,WAAW,MAAsB;CAC/C,OAAO,KAAK,QAAQ,WAAW,SAAS,KAAK,SAAS,IAAI;AAC5D;;;;;;;;AASA,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,KAAK,QAAQ,aAAa,SAAS,UAAU,SAAS,IAAI;AACnE;;;;;;;;;AAUA,SAAgB,aAAa,MAAsB;CACjD,OAAO,KAAK,QAAQ,uBAAuB,MAAM;AACnD;;;;;;;;;;;;AAaA,SAAgB,eAAe,MAAsB;CACnD,OAAO,KAAK,QAAQ,aAAa,GAAG,CAAC,CAAC,QAAQ,mBAAmB,MAAM;AACzE;;;;;;;;AASA,SAAgB,mBAAmB,MAAsB;CACvD,OAAO,KAAK,WAAW,KAAK,KAAK,CAAC,CAAC,WAAW,MAAM,KAAK,CAAC,CAAC,WAAW,MAAM,KAAK;AACnF;;;;;;;;AASA,SAAgB,uBAAuB,MAAsB;CAC3D,OAAO,mBAAmB,IAAI,CAAC,CAAC,WAAW,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,KAAK;AAC9E"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/english.ts","../src/search.ts"],"sourcesContent":["/**\n * This module has the English word forms.\n */\n\n/**\n * This function gives a count with a noun, for example \"1 site\" or \"1,024 sites\". Only the count 1 takes the singular\n * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most\n * three decimal places.\n *\n * @param count - The number of things.\n * @param noun - The singular noun.\n * @param plural - The plural noun. The default is the singular noun with the letter \"s\" at the end.\n * @returns The count, a space and the noun.\n */\nexport function countOf(count: number, noun: string, plural = `${noun}s`): string {\n return `${count.toLocaleString(\"en\")} ${count === 1 ? noun : plural}`;\n}\n","/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,QAAQ,OAAe,MAAc,SAAS,GAAG,KAAK,IAAY;CAChF,OAAO,GAAG,MAAM,eAAe,IAAI,EAAE,GAAG,UAAU,IAAI,OAAO;AAC/D;;;;;;;ACVA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * A secret to remove from a text. A string is a key, a token or a password. A pair of a user and a password is an HTTP
3
+ * Basic credential: the function also removes the password and the Base64 form of `user:password`.
4
+ */
5
+ export type Secret = string | {
6
+ readonly user: string;
7
+ readonly password: string;
8
+ };
9
+ /** The options of `redactSecrets`. */
10
+ export interface RedactOptions {
11
+ /** The text in place of each secret. The default is `[secret]`. */
12
+ readonly mark?: string;
13
+ }
14
+ /**
15
+ * This function removes each secret from a text, and puts a mark in its place. It removes these forms of each secret:
16
+ *
17
+ * - The raw form.
18
+ * - The form of `encodeURIComponent`, for a secret in the path or the query of a URL.
19
+ * - The form of `URLSearchParams`, for a secret in a query or in the body of an HTML form.
20
+ * - For a pair of a user and a password, the forms of the password and of the Base64 form of `user:password`. This
21
+ * form is the value of an HTTP `Authorization: Basic` header.
22
+ *
23
+ * The function examines the text one time, from the start. At each position, it removes the longest form that agrees.
24
+ * Thus a secret that contains a second secret goes as one mark. The function ignores an empty secret and an empty
25
+ * password. The user of a pair stays, because a user name is not a secret. To remove the user, give it as a string also.
26
+ *
27
+ * @param text - The text, for example an error message.
28
+ * @param secrets - The secrets to remove.
29
+ * @param options - The mark in place of each secret.
30
+ * @returns The text with a mark in place of each form of each secret.
31
+ */
32
+ export declare function redactSecrets(text: string, secrets: readonly Secret[], options?: RedactOptions): string;
33
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","names":[],"sources":["../src/redact.ts"],"mappings":";;;;YAWY;WAA6B;WAAuB;;;iBAG/C;;WAEN;;;;;;;;;;;;;;;;;;;;wBA2DK,cAAc,cAAc,kBAAkB,UAAU,UAAS"}
@@ -0,0 +1,74 @@
1
+ import { i as escapeRegExp } from "./escape-vfOeIxac.js";
2
+ // src/redact.ts
3
+ /**
4
+ * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than
5
+ * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes
6
+ * each form.
7
+ */
8
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9
+ /**
10
+ * The Base64 form of the UTF-8 bytes of a text, with the padding `=`, as RFC 4648 section 4 tells. A lone surrogate
11
+ * gives the bytes of U+FFFD, as the encoders of the platforms do.
12
+ */
13
+ function base64(text) {
14
+ const bytes = (encodeURIComponent(text.toWellFormed()).match(/%..|./g) ?? []).map((part) => part.length === 3 ? Number.parseInt(part.slice(1), 16) : part.charCodeAt(0));
15
+ let out = "";
16
+ for (let index = 0; index < bytes.length; index += 3) {
17
+ const [first = 0, second, third] = bytes.slice(index, index + 3);
18
+ const group = first << 16 | (second ?? 0) << 8 | (third ?? 0);
19
+ out += BASE64.charAt(group >> 18) + BASE64.charAt(group >> 12 & 63);
20
+ out += second === void 0 ? "==" : BASE64.charAt(group >> 6 & 63) + (third === void 0 ? "=" : BASE64.charAt(group & 63));
21
+ }
22
+ return out;
23
+ }
24
+ /**
25
+ * The forms of a text in a URL: the raw form, the form of `encodeURIComponent` and the form of `URLSearchParams`. The
26
+ * last form goes into a query or the body of an HTML form. It also encodes `!'()~`, and it gives `+` for a space. A
27
+ * lone surrogate is not in a URL, so the URL forms have U+FFFD in its place, as `URLSearchParams` does.
28
+ */
29
+ function urlForms(text) {
30
+ const encoded = encodeURIComponent(text.toWellFormed());
31
+ return [
32
+ text,
33
+ encoded,
34
+ encoded.replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+")
35
+ ];
36
+ }
37
+ /** Each form of a secret. */
38
+ function formsOf(secret) {
39
+ if (typeof secret === "string") return urlForms(secret);
40
+ const credential = base64(`${secret.user}:${secret.password}`);
41
+ return [...urlForms(secret.password), ...urlForms(credential)];
42
+ }
43
+ /**
44
+ * This function removes each secret from a text, and puts a mark in its place. It removes these forms of each secret:
45
+ *
46
+ * - The raw form.
47
+ * - The form of `encodeURIComponent`, for a secret in the path or the query of a URL.
48
+ * - The form of `URLSearchParams`, for a secret in a query or in the body of an HTML form.
49
+ * - For a pair of a user and a password, the forms of the password and of the Base64 form of `user:password`. This
50
+ * form is the value of an HTTP `Authorization: Basic` header.
51
+ *
52
+ * The function examines the text one time, from the start. At each position, it removes the longest form that agrees.
53
+ * Thus a secret that contains a second secret goes as one mark. The function ignores an empty secret and an empty
54
+ * password. The user of a pair stays, because a user name is not a secret. To remove the user, give it as a string also.
55
+ *
56
+ * @param text - The text, for example an error message.
57
+ * @param secrets - The secrets to remove.
58
+ * @param options - The mark in place of each secret.
59
+ * @returns The text with a mark in place of each form of each secret.
60
+ */
61
+ function redactSecrets(text, secrets, options = {}) {
62
+ const mark = options.mark ?? "[secret]";
63
+ const forms = /* @__PURE__ */ new Set();
64
+ for (const secret of secrets) {
65
+ if ((typeof secret === "string" ? secret : secret.password) === "") continue;
66
+ for (const form of formsOf(secret)) forms.add(form);
67
+ }
68
+ if (forms.size === 0) return text;
69
+ const pattern = [...forms].sort((left, right) => right.length - left.length).map(escapeRegExp).join("|");
70
+ return text.replace(new RegExp(pattern, "g"), () => mark);
71
+ }
72
+ export { redactSecrets };
73
+
74
+ //# sourceMappingURL=redact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.js","names":[],"sources":["../src/redact.ts"],"sourcesContent":["/**\n * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than\n * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes\n * each form.\n */\nimport { escapeRegExp } from \"./escape.ts\";\n\n/**\n * A secret to remove from a text. A string is a key, a token or a password. A pair of a user and a password is an HTTP\n * Basic credential: the function also removes the password and the Base64 form of `user:password`.\n */\nexport type Secret = string | { readonly user: string; readonly password: string };\n\n/** The options of `redactSecrets`. */\nexport interface RedactOptions {\n /** The text in place of each secret. The default is `[secret]`. */\n readonly mark?: string;\n}\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/**\n * The Base64 form of the UTF-8 bytes of a text, with the padding `=`, as RFC 4648 section 4 tells. A lone surrogate\n * gives the bytes of U+FFFD, as the encoders of the platforms do.\n */\nfunction base64(text: string): string {\n const bytes = (encodeURIComponent(text.toWellFormed()).match(/%..|./g) ?? []).map((part) =>\n part.length === 3 ? Number.parseInt(part.slice(1), 16) : part.charCodeAt(0),\n );\n let out = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n const [first = 0, second, third] = bytes.slice(index, index + 3);\n const group = (first << 16) | ((second ?? 0) << 8) | (third ?? 0);\n out += BASE64.charAt(group >> 18) + BASE64.charAt((group >> 12) & 63);\n out += second === undefined ? \"==\" : BASE64.charAt((group >> 6) & 63) + (third === undefined ? \"=\" : BASE64.charAt(group & 63));\n }\n return out;\n}\n\n/**\n * The forms of a text in a URL: the raw form, the form of `encodeURIComponent` and the form of `URLSearchParams`. The\n * last form goes into a query or the body of an HTML form. It also encodes `!'()~`, and it gives `+` for a space. A\n * lone surrogate is not in a URL, so the URL forms have U+FFFD in its place, as `URLSearchParams` does.\n */\nfunction urlForms(text: string): string[] {\n const encoded = encodeURIComponent(text.toWellFormed());\n const form = encoded.replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, \"+\");\n return [text, encoded, form];\n}\n\n/** Each form of a secret. */\nfunction formsOf(secret: Secret): string[] {\n if (typeof secret === \"string\") return urlForms(secret);\n const credential = base64(`${secret.user}:${secret.password}`);\n return [...urlForms(secret.password), ...urlForms(credential)];\n}\n\n/**\n * This function removes each secret from a text, and puts a mark in its place. It removes these forms of each secret:\n *\n * - The raw form.\n * - The form of `encodeURIComponent`, for a secret in the path or the query of a URL.\n * - The form of `URLSearchParams`, for a secret in a query or in the body of an HTML form.\n * - For a pair of a user and a password, the forms of the password and of the Base64 form of `user:password`. This\n * form is the value of an HTTP `Authorization: Basic` header.\n *\n * The function examines the text one time, from the start. At each position, it removes the longest form that agrees.\n * Thus a secret that contains a second secret goes as one mark. The function ignores an empty secret and an empty\n * password. The user of a pair stays, because a user name is not a secret. To remove the user, give it as a string also.\n *\n * @param text - The text, for example an error message.\n * @param secrets - The secrets to remove.\n * @param options - The mark in place of each secret.\n * @returns The text with a mark in place of each form of each secret.\n */\nexport function redactSecrets(text: string, secrets: readonly Secret[], options: RedactOptions = {}): string {\n const mark = options.mark ?? \"[secret]\";\n const forms = new Set<string>();\n for (const secret of secrets) {\n if ((typeof secret === \"string\" ? secret : secret.password) === \"\") continue;\n for (const form of formsOf(secret)) forms.add(form);\n }\n if (forms.size === 0) return text;\n const pattern = [...forms]\n .sort((left, right) => right.length - left.length)\n .map(escapeRegExp)\n .join(\"|\");\n return text.replace(new RegExp(pattern, \"g\"), () => mark);\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,SAAS;;;;;AAMf,SAAS,OAAO,MAAsB;CACpC,MAAM,SAAS,mBAAmB,KAAK,aAAa,CAAC,CAAC,CAAC,MAAM,QAAQ,KAAK,CAAC,EAAA,CAAG,KAAK,SACjF,KAAK,WAAW,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,KAAK,WAAW,CAAC,CAC5E;CACA,IAAI,MAAM;CACV,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,CAAC,QAAQ,GAAG,QAAQ,SAAS,MAAM,MAAM,OAAO,QAAQ,CAAC;EAC/D,MAAM,QAAS,SAAS,MAAQ,UAAU,MAAM,KAAM,SAAS;EAC/D,OAAO,OAAO,OAAO,SAAS,EAAE,IAAI,OAAO,OAAQ,SAAS,KAAM,EAAE;EACpE,OAAO,WAAW,KAAA,IAAY,OAAO,OAAO,OAAQ,SAAS,IAAK,EAAE,KAAK,UAAU,KAAA,IAAY,MAAM,OAAO,OAAO,QAAQ,EAAE;CAC/H;CACA,OAAO;AACT;;;;;;AAOA,SAAS,SAAS,MAAwB;CACxC,MAAM,UAAU,mBAAmB,KAAK,aAAa,CAAC;CAEtD,OAAO;EAAC;EAAM;EADD,QAAQ,QAAQ,aAAa,SAAS,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAAG,CAAC,CAAC,QAAQ,QAAQ,GAC9F;CAAC;AAC7B;;AAGA,SAAS,QAAQ,QAA0B;CACzC,IAAI,OAAO,WAAW,UAAU,OAAO,SAAS,MAAM;CACtD,MAAM,aAAa,OAAO,GAAG,OAAO,KAAK,GAAG,OAAO,UAAU;CAC7D,OAAO,CAAC,GAAG,SAAS,OAAO,QAAQ,GAAG,GAAG,SAAS,UAAU,CAAC;AAC/D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,cAAc,MAAc,SAA4B,UAAyB,CAAC,GAAW;CAC3G,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,UAAU,SAAS;EAC5B,KAAK,OAAO,WAAW,WAAW,SAAS,OAAO,cAAc,IAAI;EACpE,KAAK,MAAM,QAAQ,QAAQ,MAAM,GAAG,MAAM,IAAI,IAAI;CACpD;CACA,IAAI,MAAM,SAAS,GAAG,OAAO;CAC7B,MAAM,UAAU,CAAC,GAAG,KAAK,CAAC,CACvB,MAAM,MAAM,UAAU,MAAM,SAAS,KAAK,MAAM,CAAC,CACjD,IAAI,YAAY,CAAC,CACjB,KAAK,GAAG;CACX,OAAO,KAAK,QAAQ,IAAI,OAAO,SAAS,GAAG,SAAS,IAAI;AAC1D"}
package/package.json CHANGED
@@ -1,14 +1,18 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/text",
4
- "version": "0.0.2",
5
- "description": "Plain text helpers. The first group is the escapes: escapeHtml, escapeAttribute, escapeRegExp, escapeMarkdown, escapeWorkflowData and escapeWorkflowProperty.",
4
+ "version": "0.0.4",
5
+ "description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch) and the removal of secrets (redactSecrets).",
6
6
  "keywords": [
7
7
  "text",
8
8
  "escape",
9
9
  "html",
10
10
  "regexp",
11
11
  "markdown",
12
+ "search",
13
+ "plural",
14
+ "redact",
15
+ "secrets",
12
16
  "typescript"
13
17
  ],
14
18
  "homepage": "https://github.com/mark1russell7/text#readme",
@@ -31,6 +35,10 @@
31
35
  "types": "./build/index.d.ts",
32
36
  "default": "./build/index.js"
33
37
  },
38
+ "./redact": {
39
+ "types": "./build/redact.d.ts",
40
+ "default": "./build/redact.js"
41
+ },
34
42
  "./package.json": "./package.json"
35
43
  },
36
44
  "files": [
@@ -48,7 +56,7 @@
48
56
  "@mark1russell7/cue": "^2.0.0",
49
57
  "@mark1russell7/rigor-generators": "^0.1.8",
50
58
  "@types/node": "^26.6.5",
51
- "@vitest/coverage-v8": "5.1.0",
59
+ "@vitest/coverage-v8": "^5.0.3",
52
60
  "esbuild": "^0.28.2",
53
61
  "tsdown": "^0.23.7",
54
62
  "typescript": "^7.0.2",
package/src/english.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * This module has the English word forms.
3
+ */
4
+
5
+ /**
6
+ * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
7
+ * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
8
+ * three decimal places.
9
+ *
10
+ * @param count - The number of things.
11
+ * @param noun - The singular noun.
12
+ * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
13
+ * @returns The count, a space and the noun.
14
+ */
15
+ export function countOf(count: number, noun: string, plural = `${noun}s`): string {
16
+ return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
17
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  /**
2
- * The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes,
3
- * regular expressions, Markdown and GitHub Actions workflow commands.
2
+ * The entry of `@mark1russell7/text`: plain text helpers. The groups are the escapes for HTML, attributes, regular
3
+ * expressions, Markdown and GitHub Actions workflow commands, the English word forms and a word search. The entry
4
+ * `@mark1russell7/text/redact` removes secrets from a text.
4
5
  */
6
+ export { countOf } from "./english.ts";
5
7
  export { escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty } from "./escape.ts";
8
+ export { searchKey, wordSearch } from "./search.ts";
package/src/redact.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than
3
+ * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes
4
+ * each form.
5
+ */
6
+ import { escapeRegExp } from "./escape.ts";
7
+
8
+ /**
9
+ * A secret to remove from a text. A string is a key, a token or a password. A pair of a user and a password is an HTTP
10
+ * Basic credential: the function also removes the password and the Base64 form of `user:password`.
11
+ */
12
+ export type Secret = string | { readonly user: string; readonly password: string };
13
+
14
+ /** The options of `redactSecrets`. */
15
+ export interface RedactOptions {
16
+ /** The text in place of each secret. The default is `[secret]`. */
17
+ readonly mark?: string;
18
+ }
19
+
20
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
21
+
22
+ /**
23
+ * The Base64 form of the UTF-8 bytes of a text, with the padding `=`, as RFC 4648 section 4 tells. A lone surrogate
24
+ * gives the bytes of U+FFFD, as the encoders of the platforms do.
25
+ */
26
+ function base64(text: string): string {
27
+ const bytes = (encodeURIComponent(text.toWellFormed()).match(/%..|./g) ?? []).map((part) =>
28
+ part.length === 3 ? Number.parseInt(part.slice(1), 16) : part.charCodeAt(0),
29
+ );
30
+ let out = "";
31
+ for (let index = 0; index < bytes.length; index += 3) {
32
+ const [first = 0, second, third] = bytes.slice(index, index + 3);
33
+ const group = (first << 16) | ((second ?? 0) << 8) | (third ?? 0);
34
+ out += BASE64.charAt(group >> 18) + BASE64.charAt((group >> 12) & 63);
35
+ out += second === undefined ? "==" : BASE64.charAt((group >> 6) & 63) + (third === undefined ? "=" : BASE64.charAt(group & 63));
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /**
41
+ * The forms of a text in a URL: the raw form, the form of `encodeURIComponent` and the form of `URLSearchParams`. The
42
+ * last form goes into a query or the body of an HTML form. It also encodes `!'()~`, and it gives `+` for a space. A
43
+ * lone surrogate is not in a URL, so the URL forms have U+FFFD in its place, as `URLSearchParams` does.
44
+ */
45
+ function urlForms(text: string): string[] {
46
+ const encoded = encodeURIComponent(text.toWellFormed());
47
+ const form = encoded.replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
48
+ return [text, encoded, form];
49
+ }
50
+
51
+ /** Each form of a secret. */
52
+ function formsOf(secret: Secret): string[] {
53
+ if (typeof secret === "string") return urlForms(secret);
54
+ const credential = base64(`${secret.user}:${secret.password}`);
55
+ return [...urlForms(secret.password), ...urlForms(credential)];
56
+ }
57
+
58
+ /**
59
+ * This function removes each secret from a text, and puts a mark in its place. It removes these forms of each secret:
60
+ *
61
+ * - The raw form.
62
+ * - The form of `encodeURIComponent`, for a secret in the path or the query of a URL.
63
+ * - The form of `URLSearchParams`, for a secret in a query or in the body of an HTML form.
64
+ * - For a pair of a user and a password, the forms of the password and of the Base64 form of `user:password`. This
65
+ * form is the value of an HTTP `Authorization: Basic` header.
66
+ *
67
+ * The function examines the text one time, from the start. At each position, it removes the longest form that agrees.
68
+ * Thus a secret that contains a second secret goes as one mark. The function ignores an empty secret and an empty
69
+ * password. The user of a pair stays, because a user name is not a secret. To remove the user, give it as a string also.
70
+ *
71
+ * @param text - The text, for example an error message.
72
+ * @param secrets - The secrets to remove.
73
+ * @param options - The mark in place of each secret.
74
+ * @returns The text with a mark in place of each form of each secret.
75
+ */
76
+ export function redactSecrets(text: string, secrets: readonly Secret[], options: RedactOptions = {}): string {
77
+ const mark = options.mark ?? "[secret]";
78
+ const forms = new Set<string>();
79
+ for (const secret of secrets) {
80
+ if ((typeof secret === "string" ? secret : secret.password) === "") continue;
81
+ for (const form of formsOf(secret)) forms.add(form);
82
+ }
83
+ if (forms.size === 0) return text;
84
+ const pattern = [...forms]
85
+ .sort((left, right) => right.length - left.length)
86
+ .map(escapeRegExp)
87
+ .join("|");
88
+ return text.replace(new RegExp(pattern, "g"), () => mark);
89
+ }
package/src/search.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,
3
+ * in any order. The case of the letters is not significant.
4
+ */
5
+
6
+ /** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
7
+ const FINAL_SIGMA = /ς/gu;
8
+
9
+ /**
10
+ * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
11
+ *
12
+ * 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
13
+ * with ASCII letters.
14
+ * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
15
+ * "ss".
16
+ * 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
17
+ * 4. It applies NFKC again.
18
+ *
19
+ * The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
20
+ * Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
21
+ *
22
+ * @param text - The plain text.
23
+ * @returns The search key of the text.
24
+ */
25
+ export function searchKey(text: string): string {
26
+ return text.normalize("NFKC").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, "σ").normalize("NFKC");
27
+ }
28
+
29
+ /**
30
+ * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
31
+ * the key into words at each run of white space, the class `\s` of a regular expression.
32
+ *
33
+ * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
34
+ * search "art" finds "Party". A search with no words agrees with each text.
35
+ *
36
+ * @param query - The search, as a person types it.
37
+ * @returns The test of a text.
38
+ */
39
+ export function wordSearch(query: string): (text: string) => boolean {
40
+ const words = searchKey(query)
41
+ .split(/\s+/u)
42
+ .filter((word) => word !== "");
43
+ return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));
44
+ }